Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

276
Visualizações
Unexpected end of JSON input - Plain JS

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)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda