这是代码:
app.use(cors({
origin: 'http://localhost',
credentials: true
}));
const token = generateToken(user._id);
const cookieOptions = {
expires: new Date(Date.now() + process.env.COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000),
httpOnly: false,
sameSite: 'none',
secure: false
}
res.cookie('jwt',token,cookieOptions);
最后在客户端:
const res = await axios({
method: 'POST',
url: 'http://127.0.0.1:80/api/v1/users/login',
withCredentials: true ,
data: {
email,
password
}
})
console.log('Response : ', res);
我尝试从 -localhost/login 路由登录,每次成功登录后都会将 cookie 发送到浏览器。 但是当我尝试访问此 -localhost/tours 路线时,cookie 丢失了
您遇到的错误消息表明,当您的应用程序通过 HTTP 运行时,您正在尝试设置 SameSite=None 但没有 Secure 属性的 cookie。
生产应该是这样的:
res.cookie("jwt", jwtToken, {
httpOnly: true,
secure: true, // Ensure this is true in production
sameSite: "None", // This allows cross-site requests
maxAge: 24 * 60 * 60 * 1000, // 1 day
path: "/",
});
对于本地发展来说应该是这样的:
res.cookie("jwt", jwtToken, {
httpOnly: true,
secure: false, // Set to false for local development
sameSite: "Lax", // Or "Strict"
maxAge: 24 * 60 * 60 * 1000, // 1 day
path: "/",
});