代理原理:
客户端域名访问服务器域名,客户端域名与服务器域名不在同一域名下,存在跨域问题。
客户端通过中间件发送接收数据。间件没有axios,并且与客户端在同一域名下,从而实现跨域解决。
请求一个服务器数据
接口请求使用本地客户端域名的接口地址,pageage.json设置proxy属性,设置转接服务器的域名
当请求数据时,在pulic下进行本地数据请求,当没有从本地获取到数据,转接到服务器中进行数据获取
请求多个服务器数据
src目录下创建setupProxy.js文件,创建proxy文件
17.x版本使用:const proxy = require('http-proxy-middleware')
18.x版本使用:const {createProxyMiddleware} = require('http-proxy-middleware')
const {createProxyMiddleware}=require('http-proxy-middleware')
moudule.exports=function(app){
app.use(
createProxyMiddleware(
'/api1',{ //遇见api1前缀,触发代理配置
target:'http://localhost:5000', //请求转发的目标地址
changeOrigin:true, //服务器接收到的host值,true为目标地址,false为本地地址
pathRewrite:{ //重写请求路径
'^/api1':''
}
}
),
createProxyMiddleware(
'/api2',{
target:'http://localhost:5001',
changeOrigin:true,
pathRewrite:{
'^/api2':''
}
}
)
)
}