1、使用react-fetch数据发送请求
(1)get方法:
componentDidMount() {
fetch('url')
.then(res => res.json())
.then(json => this.setState({ list: json }))
}
(2)post方法:
componentDidMount() {
fetch('url', {
method: 'post', //改成post
mode: 'cors', //跨域
headers: { //请求头
'Content-Type': 'application/x-www-form-urlencoded'
},
body: "..." //向服务器发送的数据
})
.then(res=> res.json())
.then(json => {
console.log(json)
})
}
2、利用axios请求数据
(1)、安装axios
npm isntall axios --save
(2)、引入axios
import axios from 'axios';
(3)、发送请求
axios({
method:"POST/GET",
headers:{'Content-type':'application/json'},
url:URL+url,
data:data,
// withCredentials:true 跨域请求设置withCredentials
}).then( res => {
console.log(res);
callback(that,res);
}).catch( error => {
console.log(error);
});
}
3、GET请求获取本地数据json
(1)、在package.json文件里加上
"proxy": "http://localhost:3000"
如下图一
(2)、执行npm start
(3)、把json放到public目录下
如下图三
(4)、使用GET;POST无法请求本地数据
componentDidMount() {
fetch('./data.json', {
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => response.json()) //解析为Promise
.then(data => {
this.setState({ data: data }) //赋值到本地数据
console.log(this.state.data)
})
}
4、使用json-server请求虚拟数据
(1)、安装json-server
npm install json-server -g
使用json-server -h 来查看是否安装成功
(2)、在src同级目录下创建mock文件夹,新建data.json 写入数据
如下图二
(3)、打开新的终端输入
json-server mock/data.json -p 3000
(4)、在package.json文件中添加
"proxy":"http://localhost:3000"
(5)、重新运行npm start
(6)、发送请求
componentDidMount() {
fetch("/data.json", { method: 'GET' })
.then( res => res.json())
console.log(res)
.then( data =>
console.log(data);
)
});
}
图一:
图二
图三