How does connect's session work? I'm following this tutorial. I've noticed that even though i've commented out the session.save()
call everything still works, that property still gets persisted to the session. Does Express automatically call session.save()
every time a response is served up? If that's the case, what is the purpose of the save method?
var BaseController = require('./Base'),
View = require('../views/Base');
module.exports = BaseController.extend({
name: 'Admin',
username: 'dadams',
password: 'dadams',
run: function(req, res, next) {
if(this.authorize(req)) {
req.session.fastdelivery = true;
// req.session.save(function(err) {
var v = new View(res, 'admin');
v.render({
title: 'Administration',
content: 'Welcome to the control panel'
});
// });
} else {
var v = new View(res, 'admin-login');
v.render({
title: 'Please login'
});
}
},
authorize: function(req) {
return (
req.session &&
req.session.fastdelivery &&
req.session.fastdelivery === true
) || (
req.body &&
req.body.username === this.username &&
req.body.password === this.password
);
}
});
Connect’s session handling is automatic. Looking at the code, save
gets called automatically on res.end
(when your response is sent), so there’s no need to call it separately.
Consider it an implementation detail that’s exposed to you. I can’t think of many reasons why you would use it. Maybe if you are saving to Redis or a database and you want the session to be committed early for some reason, before calling end?