【发布时间】: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