一、本地环境——使用vue.config.js配置了跨域代理
本来发现问题,是因为后台记录到接收到的sessionId一直在变化,导致需要在同一个sessionId下处理的逻辑无法实现。
一开始以为是前后端分离跨域导致的,网上给出了解决方案:
main.js中加入以下:
 import axios from 'axios'
 axios.defaults.withCredentials = true接口文件api.js中设置每次携带cookie
axios.defaults.withCredentials = true; //意思是携带cookie信息,保持session的一致性且每次提交请求时设置:
withCredentials: true,
crossDomain: true,
export const login = (data) => {
    return axios({
        method: 'post',
        url: '/ppc_pas/user/login',
        data,
        withCredentials: true,
        crossDomain: true,
    });
}后来才发现前端发的请求都没有带cookie,就是这里,我的之前是不带这个Cookie的
最后查到资料说如果后台返回cookie的path是'/b'而本地前端本地开发地址为localhost:8080/#/home 页面,我们需要再后端返回cookie时手动修改path路径,我这里的path后端返回的是path:/ppc_pas,只需要在vue.config.js中,添加以下代码即可正常携带cookie:
// 解决前端请求cookie丢失问题
                onProxyRes(proxyRes, req, res) {
                    var oldCookie = proxyRes.headers['set-cookie']
                    if (oldCookie == null || oldCookie.length == 0) {
                        delete proxyRes.headers['set-cookie']
                        return
                    }
                    var oldCookieItems = oldCookie[0].split(';')
                    var newCookie = ''
                    for (var i = 0; i < oldCookieItems.length; ++i) {
                        if (newCookie.length > 0)
                            newCookie += ';'
                        if (oldCookieItems[i].indexOf('Path=') >= 0)
                            newCookie += 'Path=/'
                        else
                            newCookie += oldCookieItems[i]
                    }
                    proxyRes.headers['set-cookie'] = [newCookie]
                } 
   参考链接地址:https://www.bbsmax.com/A/KE5Qjx83dL/
二、生产环境——使用nginx进行反向代理
至此本地开发环境的cookie问题解决,但是当我将项目打包部署到nginx后,发现cookie丢失问题依然存在
其实道理是一样的,在我处理之前这里response 返回的cookie中Path=/ppc_pas,这里需要将其设置为/即可正常获取
 
   nginx的nginx.conf文件中设置proxy_cookie_path即可:
   location /api/v1 {
    proxy_pass http://120.78.192.248:8888/;
    #rewrite "^/api/v1/(.*)$" /$1 break;
    #set cookie path
    proxy_cookie_path  /ppc_pas /;
        }有人说需要设置以下,我这里是不需要,只要保证proxy_cookie_path /ppc_pas /;设置正确就可以了
    proxy_set_header   Cookie $http_cookie;
    proxy_cookie_flags ~ nosecure samesite=strict;我也有找到资料说设置proxy_cookie_domain,但是proxy_cookie_domain参数的作用是转换response的set-cookie header中的domain选项,由后端设置的域名domain转换成你的域名replacement,来保证cookie的顺利传递并写入到当前页面中,注意proxy_cookie_domain负责的只是处理response set-cookie头中的domain属性。我的理解是如果访问域名有替换才需要更改这个配置,但我这里不需要。
附上官网nginx文档:https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cookie_domain













![[飞腾]Trace32使用概述](https://img-blog.csdnimg.cn/img_convert/794d3d1c25f4b76e070a1e3cd201b0c5.png)




