Node.js + Express中的Session变量出错

时间:2014-03-01 01:01:19

标签: javascript node.js express session-variables

我正在使用Express和Node.js进行简单的项目使用会话变量,我在浏览器中有一个错误,我不知道为什么。错误是:

Express
500 TypeError: Cannot read property 'variable' of undefined
at /Users/jorgeregidor/zzz/app.js:44:24
etc.... 

当你没有声明变量session()时会发生同样的错误,但正如你在下面的代码中看到的定义如下:

app.use(express.cookieParser()); app.use(express.session({secret:“secret”}));

app.js代码的其余部分是:

 var express = require('express');
 var routes = require('./routes');
 var user = require('./routes/user');
 var database = require('./routes/database')
 var http = require('http');
 var path = require('path');


 var app = express();

 // all environments
 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.cookieParser());
 app.use(express.session({secret : "secret"}));
 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', database.show);
 app.post('/users', database.add);
 app.post('/users/del', database.del);

 app.get('/autenticacion',database.autenticar);

 app.post('/autenticacion',function(req, res){
req.session.variable = req.body.name; **//ERROR**
res.redirect('/secreta'); 
 });

 app.get('/secreta',function (req,res){
if (typeof(req.session.variable) != "undefined") **//ERROR**
    { res.render('secreta',{titulo:'secreta'});}
else {res.rendirect('/autenticar');}
 });



 http.createServer(app).listen(app.get('port'), function(){
   console.log('Express server listening on port ' + app.get('port'));
 });

1 个答案:

答案 0 :(得分:1)

这是因为app.router是在express.session之前启动的。你没有按照正确的顺序做事。

变化:

 app.use(app.router);
 app.use(express.cookieParser());
 app.use(express.session({secret : "secret"}));

对此:

 app.use(express.cookieParser());
 app.use(express.session({secret : "secret"}));
 app.use(app.router);