I get a problem with sessions on my ExpressJS App. In local it works perfectly but when I host my App on AppFog I get some issues with the sessions, they are lost sometimes... In my admin panel.
I don't know why but, when the page is refreshed, the sessions no longer to work...
var restrictedArea = function(req, res, next) {
if( req.session.access )
next();
else
res.redirect('/signin');
}
// Get/Post example on admin panel
app.get('/posts/add', restrictedArea, admin.addPost);
app.post('/posts/add', restrictedArea, admin.savePost);
app.post('/posts/delete', restrictedArea, admin.deletePost);
app.get('/posts/edit/:id', restrictedArea, admin.editPost);
My app.configure:
app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.static(path.join(__dirname, 'public')));
//app.use(express.session({secret: 'some secret'}));
app.use(express.cookieSession({
secret: 'SECRET',
cookie: { access: false }
})
);
app.use(express.session({secret: 'some secret'}));
app.use(app.router);
app.use(function(req, res, next){
res.render('404.jade', {
title: "404 - Page Not Found",
showFullNav: false,
status: 404,
url: req.url
});
});
});
My route:
exports.authenticate = function(req, res) {
if( req.body.username == user.username && req.body.password == user.password ){
req.session.access = true;
renderToAdminIndex(req, res);
}else{
req.session.access = false;
renderToSignin(req, res, "Error, please try again!");
}
}
signout function:
exports.signout = function(req, res) {
req.session.destroy(function(){
res.redirect('/');
});
}
Anthony
If your using express 3.x you need to use express.cookieSession
:
app.configure(function () {
...
app.use(express.cookieParser());
app.use(express.cookieSession(
{
secret: 'SECRET',
cookie: { maxAge: ... }
}
));
reference: http://expressjs.com/api.html#cookieSession
UPDATE
To wipeout the session:
exports.signout = function(req, res) {
req.session = null;
res.redirect('/');
}
来源:https://stackoverflow.com/questions/15036322/sessions-on-appfog-with-expressjs