expressjs 不能从request对象中获取Cookie?
各位大牛,请教个问题: 我expressjs开发web应用,在routes中获取不到cookie,代码如下
exports.savePage = function (req,res){
var uid;
var token;
if(req.cookies){//这个永远为空,在这里断点,浏览器调试发现请求中没有cookie
uid = req.cookies.uid;
}
.....
res.render(.....)//在完成render后,再查看浏览器调试请求中又出现了cookie
}
通过chrome调试模式下的调试发现,当连接服务端时一开始是没有,当完成服务端render操作后,浏览器调试又可以看到cookie已经上传,我一时弄不明白了,找了半天也没找到资料,请各位大牛给把把脉,谢谢了先 :)
1 回复
找到原因了,分享给大家 You need to use express.cookieParser() before app.router; middleware is run in order, meaning it’s never even reaching cookieParser() before your route is executed.
app.set(‘views’, __dirname + ‘/views’); app.set(‘view engine’, ‘jade’); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(app.router); app.use(express.static(__dirname + ‘/public’));