NodeJS 为什么我的token(cookie)没有在浏览器中设置(在MERN堆栈应用程序中使用JWT)?

xghobddn  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(93)

我在授权登录时发送了一个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只是以防万一这有助于
我试过进入隐身模式,我的代码的一些变化,从我在网上看到的东西,如添加一个路径,但它没有工作。

mwkjh3gx

mwkjh3gx1#

如果您在前端使用Fetch API,请确保在请求中包含credentials: 'include'

return fetch('http://localhost:4000/login', {
    method: 'POST',
    credentials: 'include',
    body: JSON.stringify({
        email: '[email protected]',
        password: 'Test@123'
    })
})

如果您未指定credentials: 'include',浏览器将不会保存接收到的cookie,也不会在请求头中包含现有的cookie。
更多详情here .

相关问题