1.需求 vue项目中 有时候会遇到外源的地址 域名或端口 不一致 就会 跨域
配置.在vue.config.js(有的不是这个文件) 中 配置 webpack-dev-server(可以找项目中这个的配置地方).
重要代码:
proxy: {
'/api':{ //代码加载的时候 用 /api 替换 target的地址
target:'http://222.6.10.14:70', //API服务器的地址 报跨域的地址(外源的地址)
ws:true,
changeOrigin: true, //是否跨域
// secure: true,
pathRewrite: {
'^/api': '' //需要rewrite的 把请求接口中多余的/api替换掉,
}
}
}
//请求: 注意 /api
axios({
url: "/api/aaa/bb",
}).then((data) => {
}).catch(()=>{})
devServer: {
open: true,
host: 'localhost',
port: 8888,
https: false,
hotOnly: false,
before: app => {},
proxy: {
'/api':{ //代码加载的时候 用 /api 替换 target的地址
target:'http://222.6.10.14:70', //API服务器的地址 报跨域的地址(外源的地址)
ws:true,
changeOrigin: true, //是否跨域
// secure: true,
pathRewrite: {
'^/api': '' //需要rewrite的 把请求接口中多余的/api替换掉,
}
}
}
},
//例如 vue页面请求
axios({
url: "/api/aaa/bb",
}).then((data) => {
}).catch(()=>{})
//运行过程 /api 会被 配置的代理 target 替换 http://222.6.10.14:70/aaa/bb.
代理中的重定向 pathRewrite.如果不加 请求的接口地址:http://222.6.10.14:70/api/aaa/bb.