HTTP Cookie(也叫 Web Cookie 或浏览器 Cookie)是服务器发送到用户浏览器并保存在本地的一小块数据。浏览器会存储 cookie 并在下次向同一服务器再发起请求时携带并发送到服务器上。通常,它用于告知服务端两个请求是否来自同一浏览器——如保持用户的登录状态。Cookie 使基于无状态的 HTTP 协议记录稳定的状态信息成为了可能。


/withCredentials: true, fetch 中设置credentials: 'include',服务端也需要设置Access-Control-Allow-Credentials:true来允许,当然前提是设置了Access-Control-Allow-Origin"。若是使用 nginx 做转发需要添加以下配置location / {
add_header 'Access-Control-Allow-Origin' 'your Domain';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
proxy_set_header Cookie $http_cookie;
}public/index.html
{% endgallery %}
{% endgallery %}
{% endgallery %}
{% endgallery %}set-cookie写入失败,浏览器提示sameSite默认是Lax,因为是一个跨站请求而失败,需要我们设置SameSite属性为None解决。这就说明我当前的浏览器是不允许跨站写 cookie 的(和浏览器版本有关 后面会提到),同样跨站的 cookie 也是不允许携带的
{% endgallery %}
{% endgallery %}
{% endgallery %}localhost请求https://[测试地址]还是从localhost请求局域网ip都是一个跨站请求,需要后端设置SameSite=None;Secure,而且该设置在请求后端局域网 Ip 的时候还无效,因为 not Secure。那我们就可以从根本上解决这个问题,让他不跨站,这个时候需要我们 webpack 中的devServer出马了,只需要将请求通过 devServer 代理 从localhost-> localhost 这样开发环境就可以正常携带上 cookie 了。
{% endgallery %}withCredentials和Access-Control-Allow-Credentials,其余操作一样chrome://flags/ 搜索 Partitioned Cookies ,修改为 enabled,点击 relaunch 重启浏览器即可。