React Js:Uncaught(在promise中)SyntaxError:位于0的JSON中的意外标记<

iam*_*ham 22 javascript ajax json reactjs

我想在反应js中获取我的Json文件,因为我正在使用它fetch.但它显示错误

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

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

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

我的Json(fr.json)

{
  "greeting1": "(fr)choose an emoticon",
  "addPhoto1": "(fr)add photo",
  "close1": "(fr)close"
}
Run Code Online (Sandbox Code Playgroud)

Abd*_*UMI 31

添加两个标题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");});
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个GET请求,因此发送`Content-Type`标头是完全错误的。请求中没有内容可以描述其类型。设置`Accept`标头可以解决该问题,但是很少有服务器实际执行内容协商,因此不太可能提供帮助。OP还明确声明(在问题评论中)他们遇到了CORS错误,并且使用了错误的URL,因此不清楚为什么@iamsaksham接受此作为其问题的解决方案。 (2认同)

atc*_*way 14

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

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

  • ...这救了我;-) (2认同)
  • 这就是为我解决的。我的“src”文件夹中有 JSON。将其移至“公开”使其发挥作用。 (2认同)

Sid*_*eva 9

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

response => response.json()
Run Code Online (Sandbox Code Playgroud)

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


Aka*_*eth 7

对我有用的解决方案是:-我将data.json文件从src移到了公共目录。然后使用提取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);
        });
Run Code Online (Sandbox Code Playgroud)

问题在于,在编译react app之后,获取请求会在URL“ http:// localhost:3000 / data.json ”上查找文件,这实际上是我的react app的公共目录。但是不幸的是,在编译react app时,data.json文件没有从src移到公共目录。因此,我们必须将data.json文件从src显式移动到公共目录。


Abd*_*lam 5

当尝试从“/src”文件夹中获取数据时,我也遇到了同样的问题。将文件移动到“/public”中解决了我的问题。