I’m trying to learn how to use sessions with express. I added the following to the bottom of the app.js file that comes with express:
app.use(express.cookieParser());
app.use(express.session({ secret:"string"}));
// Routes
app.get('/', function(req, res){
req.session.visitCount = req.session.visitCount ? req.session.visitCount + 1 : 1;
res.send('You have visited this page ' + req.session.visitCount + ' times');
});
However, when I run node app.js, I get this error:
500 TypeError: Cannot set property 'visitCount' of undefined
Can anyone tell me if the syntax looks right?
Yay I found an answer! how to use sessions in express, couchDB, and node.js
“If you’re doing app.use(app.router) before the lines that set up the cookie and session handling, try moving it to after them. That fixed the same problem for me.”
Since app.use(app.router) was in the configure function, I had to move the two app.use lines to the top of the configure function.