我在授权登录时发送了一个cookie,但在查看存储在浏览器中的cookie时它不会出现。发送cookie的代码如下:
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({email})
if (!user) {
return res.status(404).json({message: 'User not found'});
}
if (!bcrypt.compareSync(password, user.password)) {
return res.status(401).json({message: 'Incorrect password'});
}
jwt.sign({email:user.email, id:user._id}, process.env.JWT_SECRET, {}, (err, token) => {
if (err) {
return res.status(500).json(err);
}
res.cookie('token', token).json(user);
});
});
HTTP响应看起来像这样:
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:5173
Vary: Origin
Access-Control-Allow-Credentials: true
Set-Cookie: token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im1hcmNvcy5zZWNvLmFuZGVyc29uQGdtYWlsLmNvbSIsImlkIjoiNjUyYmUxODk4NGE4MjE2MWM3NWY1MTcwIiwiaWF0IjoxNjk3NDY2NTU1fQ.TbzDhQgQydtppUBo4NfMWmYhtJpZWUxrvWRv4Dqqmas; Path=/
Content-Type: application/json; charset=utf-8
Content-Length: 175
ETag: W/"af-QCiPuvEnfeYRFPIjeqReewm0cLM"
Date: Mon, 16 Oct 2023 14:29:15 GMT
Connection: keep-alive
Keep-Alive: timeout=5
cookie在响应中,但没有被存储,有人知道为什么吗?我的后端是在端口4000和前端在5173只是以防万一这有助于
我试过进入隐身模式,我的代码的一些变化,从我在网上看到的东西,如添加一个路径,但它没有工作。
1条答案
按热度按时间mwkjh3gx1#
如果您在前端使用Fetch API,请确保在请求中包含
credentials: 'include'
。如果您未指定
credentials: 'include'
,浏览器将不会保存接收到的cookie,也不会在请求头中包含现有的cookie。更多详情here .