http协议,请求地址,端口三者有一个不同,就会出现跨域的问题。可以通过配置代理服务器实现跨域请求。Vue中后期通过修改config文件。
1. 具体应用场景:
前端vue场景:http://localhost:8080
后端数据请求地址:http://10.9.1.183:26000/rpc/lz/normal/bmp-manage/admin.mcht.GetMchtInfo
axios:axios直接写请求地址,会报CORS(浏览器内置的安全策略)错误,虽然请求成功了,但是浏览器报异常,数据取不到。
this.$axios.get('http://10.9.1.183:26000/rpc/lz/normal/bmp-manage/admin.mcht.GetMchtInfo').then(res => {
......
}).catch(err => {
......
})
如上代码中直接写请求地址,获取不到数据。
2. 解决方案:
vue配置代理,具体步骤如下:
- 修改项目下的vue.config.js修改devServer中的proxy。
- 修改axios中的请求地址,要以/rpc开头,示例如下:
devServer: {
host: "0.0.0.0",
port: 8080, // 端口号
https: false, // https:{type:Boolean}
open: true, // 自动启动浏览器
// 配置多个代理,只是替换域名和接口
proxy: {
"/rpc": {
target: `http://10.9.1.183:26000`, // 转发的地址(加密的时候)
changeOrigin: true,//是否跨域
logLevel: "debug",
ws:true, //如果要代理 websockets,配置这个参数
secure:false, // 如果是https接口,需要配置这个参数
pathRewrite:{ //重写请求路径
'' : ''
}
},
}
},
//修改后的地址
this.$axios.get('/rpc/lz/normal/bmp-manage/admin.mcht.GetMchtInfo').then(res => {
......
}).catch(err => {
......
})
3. 对以上图片进行分析
1. 原请求地址:/rpc/lz/normal/bmp-manage/admin.mcht.GetMchtInfo
2. node服务器遇到以/rpc开头的请求,将target加上,最后的请求地址:
http://10.9.1.183:26000/rpc/lz/normal/bmp-manage/admin.mcht.GetMchtInfo
3. pathRewrite未配置路径重写,则最后的请求地址则为target加上后面的请求地址。
4. 如果配置pathRewrite:
1)将/rpc替代为"" ,pathRewrite: { '/rpc': '' },
2)替换后的地址如下,可用于没有/rpc的情况
http://10.9.1.183:26000/lz/normal/bmp-manage/admin.mcht.GetMchtInfo
4. 重启项目
npm run serve ;重新配置config文件后,需要重启项目,才能生效。