首页 > 解决方案 > 即使使用 withCredential: true,axios 也无法发送带有请求的 cookie

问题描述

我已经像这样在服务器上设置

    app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
  res.header(
    'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization,  X-PINGOTHER'
  );
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS');
  next();
});

和客户端的axios(反应)像这样

axios.defaults.withCredentials = true;
axios('http://127.0.0.1:3001/orders', {
  method: 'GET',
  withCredentials: true
}).then(res => {
     console.log(res);
   }).catch(err => {
     console.log(err.response);
   })

当我使用 Postman 测试并直接输入 chrome 时,一切正常。知道我的代码有什么问题吗?

标签: node.jsreactjscookiescorsaxios

解决方案


现在 2020 年,Chrome 对跨域 cookie 设置添加了更多烦人的限制,您必须使用SameSiteto设置 cookie none,否则 Chrome 将拒绝发送 cookie。另外,如果设置 SameSite,则必须设置secure.

以下是如何在 nginx 中设置此更改的示例,它可能不适用于您的情况,但供参考。

proxy_cookie_path / "/; secure; SameSite=none";

推荐阅读