【发布时间】:2026-01-12 08:30:01
【问题描述】:
我正在尝试在本地文件中发出请求,但我不知道何时尝试在计算机上显示错误。是否可以获取项目中的文件?
// Option 1
componentDidMount() {
fetch('./movies.json')
.then(res => res.json())
.then((data) => {
console.log(data)
});
}
error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 --> .then(res => res.json())
// Option 2
componentDidMount() {
fetch('./movies.json', {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then( res => res.json())
.then((data) => {
console.log(data);
});
}
error1: GET http://localhost:3000/movies.json 404 (Not Found) at App.js:15 --> fetch('./movies.json', {
error2: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 --> .then(res => res.json())
// This works
componentDidMount() {
fetch('https://facebook.github.io/react-native/movies.json')
.then( res => res.json() )
.then( (data) => {
console.log(data)
})
}
【问题讨论】:
-
您将无法像那样获取它,因为您的本地服务器不知道
movies.json是什么。我建议要么使用import,要么在你的api中添加一个路由来提供文件 -
从第二个错误
GET http://localhost:3000/movies.json 404 (Not Found)看来,该文件似乎不存在。我们无法告诉您您的文件在哪里...
标签: javascript reactjs fetch-api