我正在尝试在本地文件中发出请求,但我不知道何时尝试在我的计算机上执行时显示错误。是否可以获取项目中的文件?
// 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)
})
}
最佳答案
尝试像这样将您的 json 文件放在公用文件夹中:
公共(public)/电影.json
然后使用
获取fetch('./movies.json')
或
fetch('movies.json')
我以前遇到过同样的问题。当我将 json 文件放在 public 文件夹中时,问题就解决了。 使用 fetch 时,React 通常会读取 public 文件夹中的 Assets /资源文件。
关于javascript - 获取对本地文件的请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50007055/