使用ExpressJS在AppFog上进行会话

时间:2013-02-23 02:24:36

标签: node.js session express appfog

我的ExpressJS App上的会话出现问题。在本地,它工作得很好但是当我在AppFog上托管我的应用程序时,会遇到一些会话问题,有时会丢失...在我的管理面板中。

我不知道为什么,但是,当页面刷新时,会话不再起作用......

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

我的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
        });
    });
});

我的路线:

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!");
    }
}

登出功能:

exports.signout = function(req, res) {
    req.session.destroy(function(){
        res.redirect('/');
    });
}

安东尼

1 个答案:

答案 0 :(得分:2)

如果您使用快递3.x,则需要使用express.cookieSession

app.configure(function () {

  ...

  app.use(express.cookieParser());
  app.use(express.cookieSession(
    { 
      secret: 'SECRET', 
      cookie: { maxAge: ... }
    }
  ));

参考:http://expressjs.com/api.html#cookieSession

更新

要清除会话:

exports.signout = function(req, res) {
  req.session = null;
  res.redirect('/');
}