1,在package.json文件里加上
"proxy":"http://localhost:3000"
![](https://img.haomeiwen.com/i13322668/b6455a8ce8d80d6b.png)
image.png
2,然后 执行npm start
3,把json放到public目录下
![](https://img.haomeiwen.com/i13322668/8e5b53f28d1e52e0.png)
image.png
4,app.js
注意方法一定要是GET;POST无法请求本地数据的。
import React from 'react';
import './App.css';
class Notes extends React.Component{
constructor(){
super()
this.state={
totalData:''
}
}
handleclick(){
fetch('./user.json', {
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
})
.then(response => response.json())//解析为Promise
.then(data => {
this.setState({totalData: data}) ////赋值到本地数据
console.log(this.state.totalData)
})
}
render(){
return (
<div className="App">
<button onClick={this.handleclick.bind(this)}>点我发送请求</button>
</div>
);
}
}
export default Notes;
5,打开浏览器f12
![](https://img.haomeiwen.com/i13322668/bd70ecc7a2c419b6.png)
image.png
![](https://img.haomeiwen.com/i13322668/012ae501ad674361.png)
image.png
网友评论