Javascript React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37269808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:07:09  来源:igfitidea点击:

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

javascriptjsonajaxreactjs

提问by iamsaksham

I want to fetch my Json file in react js, for this I am using fetch. But it shows an error

我想在 react js 中获取我的 Json 文件,为此我使用fetch. 但它显示一个错误

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

What could be the error, i am getting no clue. I even validated my JSON.

可能是什么错误,我不知道。我什至验证了我的 JSON。

handleGetJson(){
  console.log("inside handleGetJson");
  fetch(`./fr.json`)
    .then((response) => response.json())
    .then((messages) => {console.log("messages");});
}

My Json (fr.json)

我的 Json (fr.json)

{
  "greeting1": "(fr)choose an emoticon",
  "addPhoto1": "(fr)add photo",
  "close1": "(fr)close"
}

回答by Abdennour TOUMI

Add two headers Content-Typeand Acceptto be equal to application/json.

添加两个标题Content-TypeAccept等于application/json

handleGetJson(){
  console.log("inside handleGetJson");
  fetch(`./fr.json`, {
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }

    })
    .then((response) => response.json())
    .then((messages) => {console.log("messages");});
}

回答by Akash Kumar Seth

The solution that worked for me is that:- I moved my data.json file from src to public directory. Then used fetch API to fetch the file.

对我有用的解决方案是:- 我将 data.json 文件从 src 移动到公共目录。然后使用 fetch API 来获取文件。

fetch('./data.json').then(response => {
          console.log(response);
          return response.json();
        }).then(data => {
          // Work with JSON data here
          console.log(data);
        }).catch(err => {
          // Do something for an error here
          console.log("Error Reading data " + err);
        });

The problem was that after compiling react app the fetch request looks for the file at URL "http://localhost:3000/data.json" which is actually the public directory of my react app. But unfortunately while compiling react app data.json file is not moved from src to public directory. So we have to explicitly move data.json file from src to public directory.

问题是,在编译 react 应用程序后,获取请求会在 URL“ http://localhost:3000/data.json”中查找文件,这实际上是我的 react 应用程序的公共目录。但不幸的是,在编译 react app 时 data.json 文件没有从 src 移动到 public 目录。所以我们必须明确地将 data.json 文件从 src 移动到 public 目录。

回答by atconway

This error can be received but be aware it can be a red herring to the real issue. In my case, there wasn't an issue with the JSON as the error states, but rather a 404 was occurring that it could not pull the JSON data to process in the 1st place thus resulting in this error.

可以接收到此错误,但请注意,它可能是对真正问题的一种红鲱鱼。就我而言,错误状态下的 JSON 没有问题,而是发生了 404,它无法在第一个位置提取 JSON 数据进行处理,从而导致此错误。

The fix for this was that in order to use fetchon a .jsonfile in a local project, the .jsonfile must be accessible. This can be done by placing it in a folder such as the publicfolder in the root of the project. Once I moved the jsonfile into that folder, the 404 turned into a 200, and the Unexpected token < in JSON at position 0error was resolved.

对此问题进行修复是为了使用fetch.json的本地项目文件,该.json文件必须是可访问的。这可以通过将它放在一个文件夹中来完成,例如public项目根目录中的文件夹。一旦我将json文件移动到该文件夹​​中,404 就变成了 200,Unexpected token < in JSON at position 0错误就解决了。

回答by Siddharth Sachdeva

I was getting the same error, for me, it was because API was just returning a string however in fetch call I was expecting json :

我遇到了同样的错误,对我来说,这是因为 API 只是返回一个字符串,但是在 fetch 调用中我期待的是 json :

response => response.json()

Returning json from API resolved the issue for me, if your API is not supposed to return json then simply don't do response.json()

从 API 返回 json 为我解决了这个问题,如果您的 API 不应该返回 json,那么就不要这样做 response.json()

回答by Ashraf Zaman

It may come when the API(you are consuming) is not sending the corresponding JSON. You may experience the response as 404 page or something like HTML/XML response.

当 API(您正在使用)未发送相应的 JSON 时,它可能会出现。您可能会遇到 404 页面或类似 HTML/XML 响应的响应。

回答by Jean

Mostly this is caused with an issue in your React/Client app. Adding this line to your client package.jsonsolves it

这主要是由您的 React/Client 应用程序中的问题引起的。将此行添加到您的客户端即可package.json解决

"proxy": "http://localhost:5000/"

“代理”:“ http://localhost:5000/

Note: Replace 5000, with the port number where your server is running

注意:将 5000 替换为运行服务器的端口号

Reference: How to get create-react-app to work with a Node.js back-end API

参考:如何让 create-react-app 与 Node.js 后端 API 一起工作