node.js - 为什么我的 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
})
}
)
})
})
})
解决方案
打电话res.cookie
之前res.json
。我想您应该已经看到关于在响应即将发送后设置标头的警告。
推荐阅读
- jquery - 内容未通过 jQuery 显示在网页上
- php - PHP - 保存
- php - PHP将周数和年份转换回Carbon?
- c# - iTextSharp Helvetica 使用 ArialMT 作为实际字体
- javascript - Mongoose 从结果中排除数组中的对象
- excel - Worksheet_BeforeDoubleClick restricts double click
- php - 路线未定义[讨论]
- gradle - 由于缺少依赖项,Kotlin buildSrc 在 Gradle 4.10 上失败
- node.js - fs.rename ENOENT:没有这样的文件或目录
- php - 通过 Facebook PHP Business SDK 为广告上传视频状态