vue-cli 3.0之跨域请求代理配置及axios路径配置
问题描述:前后端分离的项目,前段node+vue。在请求服务端某接口时,需要带cookie,于是设置:axiosck.defaults.withCredentials = true。导致调用后台接口时,后台接口数据正常返回,但是前段识别为跨域,拿不到返回数据。报错如下:Failed to load http://192.168.0.222/downLoad/DownLoadCh...
问题描述:
前后端分离的项目,前段node+vue。在请求服务端某接口时,需要带cookie,于是设置:
axiosck.defaults.withCredentials = true。
导致调用后台接口时,后台接口数据正常返回,但是前段识别为跨域,拿不到返回数据。报错如下:
Failed to load http://192.168.0.222/downLoad/DownLoadCheck?fileIds=855: Response to
preflight request doesn't pass access control check: The value of the 'Access-Control-
Allow-Origin' header in the response must not be the wildcard '*' when the request's
credentials mode is 'include'. Origin 'http://192.168.0.222:9527' is therefore not allowed
access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by
the withCredentials attribute.
解决方法一:需要后台配置Origin来配合。不灵活,这里不推荐。
解决方法二:配置代理(推荐)
vue.config.js:
module.exports = {
runtimeCompiler: true,
publicPath: '/', // 设置打包文件相对路径
devServer: {
// open: process.platform === 'darwin',
// host: 'localhost',
port: 8071,
// open: true, //配置自动启动浏览器
proxy: {
'/proxyApi': {
target: 'http://192.168.0.222:10002/', // 对应自己的接口
changeOrigin: true,
ws: true,
pathRewrite: {
'^/proxyApi': ''
}
}
}
},
}
解释:proxy:代理配置。
/proxyApi:自己定义一个代理名称,将来调用接口时使用此字符串代替target中的值
target: 目标代理接口地址,一版写到域名/IP+port即可。(我这里端口本来是80,为了演示代码暂时写为10002)
pathRewrite:是指定是否将 /proxyApi替换,并指定为替换的值。这里是替换为空。
请求方式:
axios.post('/proxyApi/downLoad/DownLoadCheck?fileIds=855', {
fileIds: 855,
fileType:1
}).then((res) => {
console.log(res)
})
此时,虽然请求发送到了:http://localhost:8080/proxyApi/downLoad/DownLoadCheck?fileIds=855,控制台显示请求的地址为:http://localhost:8080/proxyApi/downLoad/DownLoadCheck?fileIds=855。但是已经代理到了地址:http://192.168.0.222:10002/downLoad/DownLoadCheck?fileIds=855。亲测可用。
完善:通过配置将请求地址配置到.env文件中实现不同环境中的动态加载。实现不修改代码切换环境。
可改写为:
module.exports = {
runtimeCompiler: true,
publicPath: '/', // 设置打包文件相对路径
devServer: {
// open: process.platform === 'darwin',
// host: 'localhost',
port: 8071,
// open: true, //配置自动启动浏览器
proxy: {
'/proxyApi': {
target: process.env.VUE_APP_ERMS_API, // 对应自己的接口
changeOrigin: true,
ws: true,
pathRewrite: {
'^/proxyApi': ''
}
}
}
},
}
.env文件配置方法参照一下链接。
https://blog.csdn.net/CaptainJava/article/details/103861623
更多推荐
所有评论(0)