Sessions on AppFog with ExpressJS

放肆的年华 提交于 2019-12-22 11:29:26

问题


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


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!