首页 > 解决方案 > 为什么我的 cookie 中的数据返回未定义?

问题描述

我想要做的是将 json web 令牌设置为 cookie。当我 console.log(token) 它被定义时,但是当我得到 cookie 时它是未定义的。我已经尝试将 res.cookie 调用移动到几个不同的地方,但我仍然认为它是未定义的

POST 请求

router.post('/', (req, res) => {
    const { errors, isValid } = validateLoginInput(req.body);
    if (!isValid) {
        return res.status(400).json(errors);
    }

    const { email, password } = req.body;
    User.findOne({ email })
        .then(user => {
            if (!user) return res.status(400).json({
                msg: 'User does not exist',
                auth: false
            });

            //Validate password
            bcrypt.compare(password, user.password)
                .then(isMatch => {
                    if (!isMatch) return res.status(400).json({ msg: 'Invalid credentials' });

                    const token = jwt.sign(
                        { id: user.id },
                        process.env.JWT_SECRET,
                        (err, token) => {
                            if (err) throw err;
                            res.json({
                                token,
                                user: {
                                    id: user.id,
                                    name: user.name,
                                    email: user.email,
                                    auth: true
                                }
                            })
                            console.log(token)
                            res.cookie('access_token', token, {
                                maxAge: 604800,
                                httpOnly: true,
                                // secure: true
                            })
                        }
                    )
                })
        })
})

标签: node.jsexpresscookies

解决方案


打电话res.cookie之前res.json。我想您应该已经看到关于在响应即将发送后设置标头的警告。


推荐阅读