javascript - react Js : Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

标签 javascript json ajax reactjs

我想在react 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");});
}

我的 Json (fr.json)

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

最佳答案

添加两个 header 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");});
}

关于javascript - react Js : Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37269808/

相关文章:

javascript - 重新初始化数据表

javascript - 通过 receiveMessage 恢复等待异步脚本

javascript - 如何使用 jquery 将 .xml 数据提取到 html 中?

ASP.NET 超链接作为更新面板触发器

jquery - 如何通过 Ajax 调用显示操作

javascript - 从字符串,javascript 中获取 x 像素值文本的最可靠方法

javascript - webapp 中的交互式绘图

javascript - 添加动态原始数据时如何向具有相同 id 的多个下拉列表添加选项

java - JSON 对象的 REST Post 不处理 java 中日期值中的空格

javascript - 如果我们得到某个结果,请重试函数 promise