Home > Mobile >  Unexpected end of JSON input - Plain JS
Unexpected end of JSON input - Plain JS

Time:10-24

This is a test program as I'm learning to work with JSON and tokens. The end point is Python Flask. It seems to work fine, even what it displays in my page is fine, only I see the error in the console.

Code:

function encodeUser(user, password) {
   var token = user   ":"   password;
   var hash = btoa(token);
   return "Basic "   hash;
}

function login(resultElement) {
    result = document.getElementById(resultElement)
    u = document.getElementById("email").value;
    p = document.getElementById("password").value;
    let xhr = new XMLHttpRequest();
    let url = config_baseurl   "/login"
    xhr.open("POST",url,true);
    xhr.setRequestHeader("Content-Type","application/json");
    xhr.setRequestHeader("Authorization", encodeUser(u, p)); 
    xhr.onreadystatechange = function() {
       txt = this.responseText;
       respJson = JSON.parse(txt);
       result.innerHTML = 'response: '   txt   '<br><br>token: '   respJson.token;
    };
     xhr.send();
}

The results display as expected in my page:

response: { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwdWJsaWNfaWQiOiI3ODIxMDVjNi00ZWRhLTQyMjMtYmQ2Yy1hMDhmMzgzNWExZmUiLCJleHAiOjE2MzQ5MjA4NDR9.iHJQf3qGOJlWcSuw-itTk-IirUGUAnmtNKyUXBDnI0Y" }

token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwdWJsaWNfaWQiOiI3ODIxMDVjNi00ZWRhLTQyMjMtYmQ2Yy1hMDhmMzgzNWExZmUiLCJleHAiOjE2MzQ5MjA4NDR9.iHJQf3qGOJlWcSuw-itTk-IirUGUAnmtNKyUXBDnI0Y

The console shows this error

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () at XMLHttpRequest.xhr.onreadystatechange (example.js:36)

CodePudding user response:

Can you try with fetch / promises? Timing stuff with XMLHttpRequest is difficult. I suspect that responseText doesn't actually have a value at the time you are decoding the JSON

Something like this

function encodeUser(user, password) {
    const token = user   ":"   password;
    const encoded = btoa(token); // NOTE: Base64 is not hashing!
    return "Basic "   encoded;
}

function login(resultElement) {
    const result = document.getElementById(resultElement);
    const u = document.getElementById("email").value;
    const p = document.getElementById("password").value;

    const url = config_baseurl   "/login";
    const init = {
        method: "POST",
        headers: {
        "Content-Type": "application/json",
        Authorization: encodeUser(u, p),
        },
    };

    fetch(url, init)
        .then(res => res.json())
        .then(data => {
            console.log({ data });
            result.innerText = data.token;
        })
        .catch(console.error);
}
  • Related