React Js:Uncaught(在promise中)SyntaxError:在位置0的JSON中意外的标记<
问题描述:
我想在反应js中获取我的Json文件,对此我使用的是fetch
。但它显示了一个错误React Js:Uncaught(在promise中)SyntaxError:在位置0的JSON中意外的标记<
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"
}
答
添加两个头Content-Type
和Accept
等于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");});
}
也许你会收到错误页面的回应,请查看开发人员工具中的网络选项卡。 – jcubic
是的。我在fr.json中得到了一些垃圾html。 – iamsaksham
好的,我解决了这个问题。首先.json需要通过'localhost'加载。所以我改变了'fetch('http://localhost/img/fr.json')'。此外,我在localhost:8080上运行我的应用程序,因此发生了CORS问题,并通过chrome插件禁用了该问题。无论如何,非常感谢@jcubic提供的支持,因为有时代码中没有任何错误。 – iamsaksham