react系列---【react数据交互】
1.数据交互
0.配置代理
1.package.json配置 ,需要重启项目
{
//配置代理
"proxy":"http://localhost:5000",
}
axios("后端的路径")
2.手动配置
1.安装依赖
cnpm i http-proxy-middleware --save
2.创建setupProxy.js文件 在src下创建文件【setupProxy.js】,内容如下:
const proxy=require("http-proxy-middleware");
module.exports=(app)=>{
app.use("/api",proxy.createProxyMiddleware({
target:"http://localhost:5000",// 你的配置代理的地址
changeOrigin:true,
pathRewrite:{
"^/api":"http://localhost:5000"// 你的配置代理的地址
}
}))
}
3.使用
axios('/api'+"后端的地址") //开发环境加"/api" 生产环境不需要加"/api"
1.axios
2.fetch
get请求
fetch("url?id=1&name=2",{
//配置项
headers:{
token:"token"
}
}).then(res=>res.json())
.then(res=>{
console.log(res)
})
Post 请求
//无文件
import qs from "qs"
fetch("url",{
method:"post",
headers:{
"Content-type":"application/x-www-form-urlencoded"
},
body:qs.stringify({
phone:"123",password:"123"
})
}).then(res=>res.json())
.then(res=>{
console.log(res)
})
//有文件
let data=new FormData()
data.append("pid",0)
data.append("catename","test")
data.append("img",this.file.current.files[0])
data.append("status",1)
fetch("/api/api/cateadd",{
method:"post",
body:data
}).then(res=>res.json()).then(res=>{
console.log(res);
})
fetch封装
import querystring from "querystring"
let baseUrl = "";
if (process.env.NODE_ENV === "development") {
baseUrl = "/api"
}
//响应拦截
function response(url, res) {
//打印数据
console.log('本次请求:' + baseUrl + url);
console.log(res);
//失败处理
if (res.code !== 200) {
alert(res.msg)
return;
}
}
/**
* url:"/api/login"
* params:{phone:11,password:123}----->phone=11&password=123
*/
export const get = (url, params = {}) => {
//先将参数转换
params = querystring.stringify(params);
return new Promise((resolve) => {
fetch(baseUrl + url + "?" + params, {
headers: {
authorization: localStorage.getItem("token")
}
}).then(res => res.json()).then(res => {
//响应拦截
response(url, res)
resolve(res)
})
})
}
/**
* url:"/api/login"
*/
export const post = (url, params = {}, isFile = false) => {
let data = null;
let headers = {
authorization: localStorage.getItem("token"),
}
if (isFile) {
//有文件
data = new FormData();
for (let i in params) {
data.append(i, params[i])
}
} else {
//无文件
data = querystring.stringify(params);
headers = {
...headers,
"Content-type": "application/x-www-form-urlencoded"
}
}
return new Promise((resolve) => {
fetch(baseUrl + url, {
method: "post",
body: data,
headers
}).then(res => res.json())
.then(res => {
//响应拦截
response(url, res);
resolve(res)
})
})
}