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

新手上路,请多包涵

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

原文由 iamsaksham 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

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

原文由 Abdennour TOUMI 发布,翻译遵循 CC BY-SA 3.0 许可协议

对我有用的解决方案是:- 我将 data.json 文件从 src 移动到 public 目录。然后使用 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);
        });

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

原文由 Akash Kumar Seth 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题