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

前端 未结 30 1471
花落未央
花落未央 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:33

    If anyone else is using fetch from the "Using Fetch" documentation on Web API's in Mozilla: (This is really useful: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)

      fetch(api_url + '/database', {
        method: 'POST', // or 'PUT'
        headers: {
         'Content-Type': 'application/json'
        },
        body: qrdata //notice that it is not qr but qrdata
      })
      .then((response) => response.json())
      .then((data) => {
        console.log('Success:', data);
      })  
      .catch((error) => {
      console.error('Error:', error);  });
    

    This was inside the function:

    async function postQRData(qr) {
    
      let qrdata = qr; //this was added to fix it!
      //then fetch was here
    }
    

    I was passing into my function qr what I believed to be an object because qr looked like this: {"name": "Jade", "lname": "Bet", "pet":"cat"} but I kept getting syntax errors. When I assigned it to something else: let qrdata = qr; it worked.

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

    Just to add to the answers, it also happens when your API response includes

    <?php{username: 'Some'}
    

    which could be a case when your backend is using PHP.

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

    In my case (backend), I was using res.send(token);

    Everything got fixed when I changed to res.send(data);

    You may want to check this if everything is working and posting as intended, but the error keeps popping up in your front-end.

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

    i was facing the same issue
    i removed the dataType:'json' from the $.ajax method

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

    Protip: Testing json on a local Node.js server? Make sure you don't already have something routing to that path

    '/:url(app|assets|stuff|etc)';
    
    0 讨论(0)
  • 2020-11-22 05:41

    This error occurs when you define the response as application/json and you are getting a HTML as a response. Basically, this happened when you are writing server side script for specific url with a response of JSON but the error format is in HTML.

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