jorgeregidor
jorgeregidor

Reputation: 208

Error with Session variables in Node.js + Express

I am making a easy proyect with Express and Node.js that use session variables and i have a Error in the browser and i don't know why. the error is:

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

It is the same error that occurs when you do not declare the variable-session (), but as you can see in the code below are defined as follows:

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

the rest of the the app.js code is:

 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'));
 });

Upvotes: 0

Views: 1048

Answers (1)

Maxime Poulin
Maxime Poulin

Reputation: 152

It's because app.router is initiated before express.session. You're not doing things in the right order.

Change:

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

To this:

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

Upvotes: 1

Related Questions