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

前端 未结 30 1470
花落未央
花落未央 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.
    0 讨论(0)
  • 2020-11-22 05:21

    I had the same error message following a tutorial. Our issue seems to be 'url: this.props.url' in the ajax call. In React.DOM when you are creating your element, mine looks like this.

    ReactDOM.render(
        <CommentBox data="/api/comments" pollInterval={2000}/>,
        document.getElementById('content')
    );
    

    Well, this CommentBox does not have a url in its props, just data. When I switched url: this.props.url -> url: this.props.data, it made the right call to the server and I got back the expected data.

    I hope it helps.

    0 讨论(0)
  • 2020-11-22 05:21

    Those who are using create-react-app and trying to fetch local json files.

    As in create-react-app, webpack-dev-server is used to handle the request and for every request it serves the index.html. So you are getting

    SyntaxError: Unexpected token < in JSON at position 0.

    To solve this, you need to eject the app and modify the webpack-dev-server configuration file.

    You can follow the steps from here.

    0 讨论(0)
  • 2020-11-22 05:22

    This ended up being a permissions problem for me. I was trying to access a url I didn't have authorization for with cancan, so the url was switched to users/sign_in. the redirected url responds to html, not json. The first character in a html response is <.

    0 讨论(0)
  • 2020-11-22 05:23

    On a general level this error occurs when a JSON object is parsed that has syntax errors in it. Think of something like this, where the message property contains unescaped double quotes:

    {
        "data": [{
            "code": "1",
            "message": "This message has "unescaped" quotes, which is a JSON syntax error."
        }]
    }
    

    If you have JSON in your app somewhere then it's good to run it through JSONLint to verify that it doesn't have a syntax error. Usually this isn't the case though in my experience, it's usually JSON returned from an API that's the culprit.

    When an XHR request is made to an HTTP API that returns a response with a Content-Type:application/json; charset=UTF-8 header which contains invalid JSON in the response body you'll see this error.

    If a server-side API controller is improperly handling a syntax error, and it's being printed out as part of the response, that will break the structure of JSON returned. A good example of this would be an API response containing a PHP Warning or Notice in the response body:

    <b>Notice</b>:  Undefined variable: something in <b>/path/to/some-api-controller.php</b> on line <b>99</b><br />
    {
        "success": false,
        "data": [{ ... }]
    }
    

    95% of the time this is the source of the issue for me, and though it's somewhat addressed here in the other responses I didn't feel it was clearly described. Hopefully this helps, if you're looking for a handy way to track down which API response contains a JSON syntax error I've written an Angular module for that.

    Here's the module:

    /**
     * Track Incomplete XHR Requests
     * 
     * Extend httpInterceptor to track XHR completions and keep a queue 
     * of our HTTP requests in order to find if any are incomplete or 
     * never finish, usually this is the source  of the issue if it's 
     * XHR related
     */
    angular.module( "xhrErrorTracking", [
            'ng',
            'ngResource'
        ] )
        .factory( 'xhrErrorTracking', [ '$q', function( $q ) {
            var currentResponse = false;
    
            return {
                response: function( response ) {
                    currentResponse = response;
                    return response || $q.when( response );
                },
                responseError: function( rejection ) {
                    var requestDesc = currentResponse.config.method + ' ' + currentResponse.config.url;
                    if ( currentResponse.config.params ) requestDesc += ' ' + JSON.stringify( currentResponse.config.params );
    
                    console.warn( 'JSON Errors Found in XHR Response: ' + requestDesc, currentResponse );
    
                    return $q.reject( rejection );
                }
            };
        } ] )
        .config( [ '$httpProvider', function( $httpProvider ) {
            $httpProvider.interceptors.push( 'xhrErrorTracking' );
        } ] );
    

    More details can be found in the blog article referenced above, I haven't posted everything found there here as it's probably not all relevant.

    0 讨论(0)
  • 2020-11-22 05:23

    In my Case there was problem with "Bearer" in header ideally it should be "Bearer "(space after the end character) but in my case it was "Bearer" there was no space after the character. Hope it helps some one!

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