“SyntaxError: Unexpected token < in JSON at position 0”

前端 未结 30 1609
花落未央
花落未央 2020-11-22 04:39

In a React app component which handles Facebook-like content feeds, I am running into an error:

Feed.js:94 undefined \"parsererror\" \"SyntaxError: Un

30条回答
  •  悲&欢浪女
    2020-11-22 05:21

    In a nutshell, if you're getting this error or similar error, that means only one thing. That is, in someplace in our codebase we were expecting a valid JSON format to process and we didn't get one. For example:

    var string = "some string";
    JSON.parse(string)
    

    Will throw an error, saying

    Uncaught SyntaxError: Unexpected token s in JSON at position 0

    Because, the first character in string is s & it's not a valid JSON now. This can throw error in between also. like:

    var invalidJSON= '{"foo" : "bar", "missedquotehere : "value" }';
    JSON.parse(invalidJSON)
    

    Will throw error:

    VM598:1 Uncaught SyntaxError: Unexpected token v in JSON at position 36
    

    because we intentionally missed a quote in the JSON string invalidJSON at position 36.

    And if you fix that:

    var validJSON= '{"foo" : "bar", "missedquotehere : "value" }';
    JSON.parse(validJSON)
    

    will give you an object in JSON.

    Now, this error can be thrown in any place & in any framework/library. Most of the time you may be reading a network response which is not valid JSON. So steps of debugging this issue can be like:

    1. curl or hit the actual API you're calling.
    2. Log/Copy the response and try to parse it with JSON.parse. If you're getting error, fix it.
    3. If not, make sure your code is not mutating/changing the original response.

提交回复
热议问题