Uncaught (in promise) SyntaxError: Unexpected end of JSON input

前端 未结 4 1311
独厮守ぢ
独厮守ぢ 2020-12-18 01:47

I am trying to send a new push subscription to my server but am encountering an error \"Uncaught (in promise) SyntaxError: Unexpected end of JSON input\" and the console say

相关标签:
4条回答
  • 2020-12-18 02:11

    For someone looking here later. I received this error not because of my headers but because I was not recursively appending the response body to a string to JSON.parse later.

    As per the MDN example (I've taken out some parts of their example not immediately relevant):

    reader.read().then(function processText({ done, value }) {
        if (done) {
          console.log("Stream complete");
          return;
        }
        result += chunk;
        return reader.read().then(processText);
      });

    For my issue I had to

    1. Use a named function (not an anonymous ()=>{}) inside the .then
    2. Append the result together recursively.
    3. Once done is true execute something else on the total appended result

    Just in case this is helpful for you in the future and your issue is not header related, but related to the done value not being true with the initial JSON stream response.

    0 讨论(0)
  • 2020-12-18 02:14

    This might be a problem with the endpoint not passing the appropriate parameters in the response's header.

    In Chrome's console, inside the Network tab, check the headers sent by the endpoint and it should contain this: Example of proper response to allow requests from localhost and cross domains requests

    Ask the API developer to include this in the headers:

    "Access-Control-Allow-Origin" : "*", 
    "Access-Control-Allow-Credentials" : true 
    
    0 讨论(0)
  • 2020-12-18 02:16

    This can be because you're not sending any JSON from the server OR This can be because you're sending invalid JSON.

    Your code might look like res.end();

    0 讨论(0)
  • 2020-12-18 02:21

    One of the pitfalls is that returned data that is not a JSON but just a plain text payload regardless of headers set. I.e. sending out in Express via something like

    res.send({a: "b"});
    

    rather than

    res.json({a: "b"});
    

    would return this confusing error. Not easy to detect in network activity as it looks quite legit.

    0 讨论(0)
提交回复
热议问题