思路 先将请求发送给本地的vue中的内置服务器 如果本地没有 就去目标服务器请求 主要看路径
-
方式一 配置 在 vue.config.js中配置 参考 cli文档
在vue.config.js中添加配置项
devServer: {
// 目标服务器 将 http://localhost:8080/test
// 解析成 http://192.168.122.22:3000/test 去发送请求 成功后再转发给前端
proxy: "http://192.168.122.22:3000",
}, 方式一的缺点是 只能有一个目标服务器 无法配置多个服务器代理
方式二 配置多个代理服务器
devServer: {
proxy: {
'/target1': {
target: 'http://localhost:3000', // 目标服务器地址
ws: true, // websocket
changeOrigin: true, // 是否改变ip原地址
pathRewrite:{ // 重写路径 将 /target1 替换成 ""
"^/target1":""
}
},
'/foo': {
target: 'url地址',
ws:true,
changeOrigin: true,
pathRewrite:{
"^/foo":""
}
}
}
}
在组件中发送请求
axios.get("http://localhost:8080/target1/test").then((res)=>{
console.log( res);
})特别注意 修改配置项后要重启 vue 服务