Search code examples
javascriptjsonxmlhttprequest

JSON.parse Unexpected end of JSON input but the code process correctly the data


I'm using a Cloudflare worker to return a JSON. The code running on the worker is pretty simple

//return JSON
    const data = {
      pswd: psk_db,
    };

    json = JSON.stringify(data, null, 2);
  }

  return new Response(json, {
      headers: {
        'content-type': 'application/json;charset=UTF-8',
        "Access-Control-Allow-Origin": "*",
      },
    })

Now, for some reason, I correctly recieve the response but when I call the javascript

var parsed = JSON.parse(Http.response);
        document.getElementById("json_response_code").textContent = parsed.pswd;

I got

Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at RequestCode.Http.onreadystatechange (index.html:83:27)

But I still correctly get the value on parsed.pswd

I can't find the issue as the code works but it throws error anyway

EDIT

Console.log(Http.response) shows

{
  "pswd": "nicola"
}

Yes, I'm using it; added code

const Http = new XMLHttpRequest();
      const url = my_url;

      Http.open("GET", url);
      Http.send();

      Http.onreadystatechange = (e) => {
        console.log(Http.response);
        var parsed = JSON.parse(Http.response);
        document.getElementById("json_response_code").textContent = parsed.pswd;
  };

Solution

  • As suggested by @Jaromanda-X Http.onreadystatechange = (e) was used in the wrong way.

    Solution has been

      Http.onload = (e) => {
        // In local files, status is 0 upon success in Mozilla Firefox
        if (Http.readyState === XMLHttpRequest.DONE) {
          const status = Http.status;
          if (status === 0 || (status >= 200 && status < 400)) {
            // The request has been completed successfully
            console.log(Http.responseText);
            var parsed = JSON.parse(Http.response);
            document.getElementById("json_response_code").textContent =
              parsed.pswd;
          } else {
            // Oh no! There has been an error with the request!
            console.log(Error);
          }
        }
      };
      Http.send();