我从头开始生成Express应用程序并添加cookieParser,session和csrf中间件
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.use(express.cookieParser());
app.use(express.session({secret: "lalala" }));
app.use(express.csrf());
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(80, function(){
console.log('Express server listening on port ' + app.get('port'));
});
然后在索引路由器中,我尝试访问会话
exports.index = function(req, res){
res.cookie('u','1');
console.log(res.session);
res.render('index', { title: 'Express' });
};
但不幸的是,它总是未定义的! 为什么呢?
答案 0 :(得分:3)
您正在查看回复(res
)而不是请求(req
)。 console.log(req.session)
应该有效。容易犯错误。