Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

277
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda