Jav*_*ier 14 javascript reactjs fetch-api
我正在尝试在本地文件中发出请求,但我不知道我何时尝试在计算机上显示错误.是否可以获取项目中的文件?
// 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)
})
}
Run Code Online (Sandbox Code Playgroud)
Ang*_*ris 16
您正尝试使用fetch命令提供静态文件,该命令本身要求服务器提供该文件.要解决此问题,您可以使用一些选项.我将概述最常用于此类事情的两个:
最后,还有其他选项可以在线上传一个或多个文件并从外部URL获取,但这可能不是最佳策略.
您的JSON文件需要由服务器提供,因此您需要快速服务器(或任何其他服务器).在这个例子中,我们使用express.
注意:您也可以下载git repo
App.js文件
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
componentDidMount() {
const myHeaders = new Headers({
"Content-Type": "application/json",
Accept: "application/json"
});
fetch("http://localhost:5000/movie", {
headers: myHeaders,
})
.then(response => {
console.log(response);
return response.json();
})
.then(data => {
console.log(data);
this.setState({ data });
});
}
render() {
return <div className="App">{JSON.stringify(this.state.data)}</div>;
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
server.js
var express = require("express");
var data = require('./movie.json'); // your json file path
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get("/movie", function(req, res, next) {
res.send(data);
});
app.listen(5000, () => console.log('Example app listening on port 5000!'))
Run Code Online (Sandbox Code Playgroud)
我遇到了同样的错误,我在代码中做了两个更改以消除错误。首先,您不需要快速服务器来为您的文件提供服务,您可以从 create-react-app 目录中公共文件夹内的本地 json 文件中读取数据。
const getData=()=>{
fetch('data.json',{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
)
.then(function(response){
console.log(response)
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
}
useEffect(()=>{
getData()
},[])
Run Code Online (Sandbox Code Playgroud)
首先,正如上面的一些答案所建议的那样,确保您的 json 文件位于 public 文件夹中,并且 fetch 函数中的 path 参数如上所述是正确的。相对路径对我不起作用。其次,如图所示设置标题。从我的 fetch 调用中删除标题部分仍然给我这个错误。
尝试将json文件放在公共文件夹中,如下所示:
public / movies.json
然后使用
fetch('./movies.json')
Run Code Online (Sandbox Code Playgroud)
要么
fetch('movies.json')
Run Code Online (Sandbox Code Playgroud)
我以前也遇到过同样的问题。当我将json文件放在公用文件夹中时,问题解决了。使用获取时,React通常会读取公用文件夹中的资产/资源文件。