我似乎无法在从Netlify进行API调用时设置cookies,但使用Postman可以工作。我不明白为什么。我的代码看起来像这样:
最后,express应用程序的配置如下:
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) => {});
最后,express应用程序的配置如下:
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();
});
我的signedcookies一直显示如下:[Object: null prototype] {}
我注意到这个问题发生在Safari上而非Chrome。
在Chrome中,请求包含accessToken
和refreshToken
。
我还注意到,如果我设置sameSite:'lax'
,那么只有refreshToken
会被保留。