如果在发送响应之前设置cookie,我会遇到问题。就像我想为登录用户设置cookie,然后我想发送响应OK。
User.find({user:req.body.username,password:req.body.password})
.exec(function(err,row){
if(err){
console.log(err);
res.negotiate();
}
else if(row.length){
res.cookie('user',{user:row[0].user,role:row[0].role},{
signed:true,
httpOnly:true,
maxAge:1000*60*60*24*5
});
res.end('You are logged in successfully');
}
else{
console.log('nothing executed');
res.end('Not such a user');
}
});
是否确定res.cookie()
将在res.end()
之前执行
通过向浏览器发送Set-Cookie
标头来"设置"cookie。因此,严格来说,在发送响应之前,不可能设置cookie。调用res.cookie()
只是准备相应的标头,但实际上并不发送它。
我看到你使用cookie来存储用户数据,所以在这种情况下,你最好使用这样的会话模块https://github.com/expressjs/session--它将允许您随时读取或写入数据,并为您处理低级cookie业务。