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

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

    SyntaxError: Unexpected token < in JSON at position 0


    You are getting an html file instead of json.

    Html files begin with .

    I "achieved" this error by forgetting the https:// in my fetch method:

    fetch(`/api.github.com/users/${login}`)
        .then(response => response.json())
        .then(setData);
    

    I verified my hunch:

    I logged the response as text instead of JSON.

    fetch(`/api.github.com/users/${login}`)
        .then(response => response.text())
        .then(text => console.log(text))
        .then(setData);
    

    Yep, an html file.

    Solution:

    I fixed the error by adding back the https:// in my fetch method.

    fetch(`https://api.github.com/users/${login}`)
        .then(response => response.json())
        .then(setData)
        .catch(error => (console.log(error)));
    

提交回复
热议问题