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-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");});
}
Run Code Online (Sandbox Code Playgroud)
atc*_*way 14
可以接收到此错误,但请注意,它可能是对真正问题的一种红鲱鱼。在我的情况下,JSON 没有问题,因为错误状态,而是发生了 404,它无法在第一个位置拉取 JSON 数据进行处理,从而导致此错误。
对此问题进行修复是为了使用fetch上.json的本地项目文件,该.json文件必须是可访问的。这可以通过将它放在一个文件夹中来完成,例如public项目根目录中的文件夹。一旦我将json文件移动到该文件夹中,404 就变成了 200,Unexpected token < in JSON at position 0错误就解决了。
我遇到了同样的错误,对我来说,这是因为 API 只是返回一个字符串,但是在 fetch 调用中我期待的是 json :
response => response.json()
Run Code Online (Sandbox Code Playgroud)
从 API 返回 json 为我解决了这个问题,如果您的 API 不应该返回 json,那么就不要这样做 response.json()
对我有用的解决方案是:-我将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显式移动到公共目录。
| 归档时间: |
|
| 查看次数: |
63037 次 |
| 最近记录: |