【问题标题】:Cookie not being set in headers using CORS with NodeJS没有在使用 CORS 和 NodeJS 的标头中设置 Cookie
【发布时间】:2021-11-12 19:36:58
【问题描述】:

我的前端和后端都位于不同的域中。我正在尝试向 Axios 发出 put 请求,以使用 express-session 对用户进行身份验证。该调用工作正常,但似乎服务器没有在响应的标头中设置 cookie。这是我的代码:

这是前端的代码:

Axios.post('/users/authenticate', {
            //DATA
        }, {withCredentials: true})
        .then((response) => {
            console.log(response);
        })
        .catch((error) =>{
            console.log(error);
        });

然后是我在 NodeJS 服务器中的代码。这是为了允许 cors:

app.use(cors({
    origin: ['http://localhost:3000'], 
    credentials: true, 
    methods: ['POST', 'PUT', 'GET', 'OPTIONS', 'HEAD', 'DELETE'],
    exposedHeaders: ["set-cookie"]
}));

然后设置cookie:

router.use(session({
    secret: 'the secret',
    cookie: {maxAge: 2000 * 60, sameSite: 'none', secure: true},
    store: store,
    resave: true,
    saveUninitialized: true,
}));

最后是我的响应头:

我已经尝试了我在 StackOverflow 和其他博客和论坛中找到的所有解决方案,其中包含 cors 中的选项,但仍然无法在 Chrome、Edge 和 Firefox 中使用,但在 Postman 中可以使用

【问题讨论】:

  • 你检查控制台日志了吗?有时有一个原因是 cors 阻止您发送请求
  • 只有通过 HTTPS 发出后端请求时才会发送 secure 会话 cookie。

标签: javascript node.js express session cookies


【解决方案1】:

我发现了问题。我仍然不确定后台发生了什么。

我必须在代码的最开始添加这一行:

app.set('trust proxy', 1);

现在可以了。我在开发工具的应用程序选项卡中看不到 cookie,但我在响应标头中看到它并且按预期工作。

我想我的前端和后端之间有一个代理。如果有人能解释一下,我将不胜感激。

【讨论】:

    猜你喜欢
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 2015-05-21
    • 2019-03-26
    • 2020-02-14
    • 2013-04-24
    相关资源
    最近更新 更多