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

Issue

This Content is from Stack Overflow. Question asked by NicoCaldo

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



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();


This Question was asked in StackOverflow by NicoCaldo and Answered by NicoCaldo It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?