【发布时间】:2020-08-15 23:39:31
【问题描述】:
如果我从 Netlify 进行 api 调用,我似乎无法设置 cookie,但使用 Postman 可以。
我不明白为什么。
我的代码如下所示:
router.post('/login', localAuth, async (req, res) => {
// The code goes through and returns status 200
return res.status(200)
.cookie('accessToken', accessToken, {
signed: true,
httpOnly: true,
secure: true,
maxAge: 15 * 60 * 1000,
sameSite: 'none', // <-- I also tried lax
}).cookie('refreshToken', refreshToken, {
signed: true,
httpOnly: true,
secure: true,
maxAge: 7 * 24 * 60 * 60 * 1000,
sameSite: 'none', // <-- I also tried lax
}).send( // something );
});
然后代码尝试不同的路由,之后由于缺少 cookie 而失败
router.get('/user', accessjwtAuth <-- this fails due to no cookies, async (req, res) => {})
Netlify 默认自带 SSL 证书。来自前端的调用如下所示:
const config = {
baseURL: `${API_URL}/api/auth/login`,
method: 'post',
withCredentials: true,
headers: {'Content-Type': 'application/json',},
data: values,
};
axios(config).then((res) => {});
最后,快递应用是这样配置的:
const allowed_origins = ["https://something.netlify.app", "localhost:8080"];
app.use(function(req, res, next) {
const origin = req.headers.origin;
if (allowed_origins.indexOf(origin) > -1) {
res.setHeader('Access-Control-Allow-Origin', origin);
};
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
我一直在为我的已签名cookies 收到这个,[Object: null prototype] {}
我注意到这个问题发生在 Safari 而不是 Chrome 上。
在 Chrome 中,req 同时具有 accessToken 和 refreshToken。
我还注意到,如果我设置 sameSite: 'lax',那么只有 refreshToken 会被保留。
【问题讨论】:
-
theverge.com/2020/3/24/21192830/… 也许你可以尝试在 Safari 中启用“跨站跟踪”,看看问题是否与它有关。
-
这确实有效。 Safari 和 Chrome 都登录并为下一次 api 调用保留了它们的令牌。不过,我不能指望用户更改该设置,那么我该从哪里修复呢?终于有东西了,谢谢。
标签: node.js express cookies netlify