React 请求Post接口
1.安装 axios
npm install axios
2.页面引入axios模块
import axios from 'axios';
3.请求接口
axios.post('/getAdd', obj)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
//必须放在useEffect函数里不然防火墙视为CC
useEffect(() => {
axios.post('/getxxxÏ', { blok: 'demo'Ï}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
}, [])
4.React 跨域网络请求接口 (根据需求是跨域)
在项目中的package.json文件中加上
"proxy": "http://127.0.0.1:8081",
接口请求时直接接口地址方式
axios.post('/getAdd', data)5.请求Get接口
axios.get('http://xxxx')
.then(response => {
console.log(response.data);// 处理返回的数据
})
.catch(error => {
console.error(error); // 处理错误
});6.上传文件接口post方式
// 发送文件上传请求
const formData = new FormData();
formData.append('files', file);
axios.post(https + '/getUpload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {// 文件上传成功处理
console.log('File uploaded:', response.data);
}).catch(error => {
console.error(error);// 错误处理
});