最近做登录的时候,会出现已经登录的情况下,其他请求未登录的情况,查看请求头的时候发现并没有把登录时的cookie设置到第二次的请求头里面。起因源码如下:
proxyTable: {
'/api': {
target: 'http://xxx.xxx.xxx.xxx:xxx', //改成第三方接口
changeOrigin: true,
pathRewrite: {
'^/api': '/api'
}
}
},
将target改成第三方接口之后报如下错:
排查原因考虑可能是跨域问题,有以下解决办法:
- 把Domain路径重写,经测有效
"/api": {
target:'http://xxx.xxx.xxx.xxx:xxx',
changeOrigin: true,
pathRewrite: {
'^/api': '/api'
},
cookieDomainRewrite: "localhost", //重写Domain
},
文档解释如下
option.cookieDomainRewrite:重写set-cookie标题的域。可能的值:
false (默认值):禁用cookie重写
字符串:例如新域cookieDomainRewrite: "new.domain"。要删除域,请使用cookieDomainRewrite: ""。
对象:将域映射到新域,用于"*"匹配所有域。
例如,保持一个域不变,重写一个域并删除其他域:
cookieDomainRewrite: {
"unchanged.domain": "unchanged.domain",
"old.domain": "new.domain",
"*": ""
}
- 在main.js文件中加上
withCredentials = true
import axios from 'axios';
Vue.prototype.$axios = axios;
axios.defaults.withCredentials = true; //加上这句
完美解决
- 考虑到是第三方域名无法被本机域名访问,让后端同事允许其他域名也能访问就可以了