在学习React时重新过了一遍axios,其中涉及到promise方法
引入axios
import axios from 'axios';axios请求正常写,post 和 put 要在参数中额外加请求体对象属性
axios({
method:'GET',
url:'http://localhost:3000/api1/students'
}).then(
response => {console.log('成功',response.data);
},
error => {console.log('失败',error);
}
)(api为代理相关)
解决跨域 在axios方法中url配置为本地url域名
单个端口的跨域:在package.json中 单独设置 "proxy": 目标端口url
多个端口的跨域:
1)在src中新建一个setupProxy.js文件
2)在setupProxy.js文件中配置多个端口的代理
const {createProxyMiddleware} = require('http-proxy-middleware')
module.exports = function(app){
app.use(
createProxyMiddleware('/api1',{ //遇见/api1前缀的请求,就会触发该代理配置
target:'http://localhost:5000', //请求转发给谁
changeOrigin:true,//控制服务器收到的请求头中Host的值
pathRewrite:{'^/api1':''} //重写请求路径(必须)
}),
createProxyMiddleware('/api2',{
target:'http://localhost:5001',
changeOrigin:true,
pathRewrite:{'^/api2':''}
}),
)
}其中涉及版本问题 低版本中的 createProxyMiddleware 用 Proxy 代替
在axios方法中添加前缀(图中api/),即可将请求发给代理,并由代理转发给目标端口,解决跨域
changeOrigin:true,//控制服务器收到的请求头中Host的值
pathRewrite:{'^/api1':''} //重写请求路径(必须)
这两个属性:
前者将欺骗服务端收到的路径
后者将欺骗浏览器收到的域名
版权声明:本文为jym115原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。