2

我在我的 ExpressJS 应用程序上遇到了会话问题。在本地它工作得很好,但是当我在 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(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('/');
    });
}

安东尼

4

1 回答 1

2

如果您使用 express 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('/');
}
于 2013-02-23T03:24:34.163 回答