Working with Sessions in Express.js

前端 未结 2 1553
天命终不由人
天命终不由人 2020-12-22 22:17

I need help understanding the concept of sessions for a web application. I am running a Node.js server with Express 3.0.

My goals are to:

  • Create a s

2条回答
  •  情深已故
    2020-12-22 23:02

    Express has nice examples in the github repo. One of them deals with authentication and shows how to attach the user to the req.session object. This is done inside the app.post('/login') route.

    To limit access to certain pages add a simple middleware to those routes

    function restrict(req, res, next) {
      if (req.session.user) {
        next();
      } else {
        req.session.error = 'Access denied!';
        res.redirect('/login');
      }
    }
    
    app.get('/restricted', restrict, function(req, res){
      res.send('Wahoo! restricted area, click to logout');
    });
    

    As Brandon already mentioned you shouldn't use the MemoryStore in production. Redis is a good alternative. Use connect-redis to access the db. An example config looks like this

    var RedisStore = require('connect-redis')(express);
    
    // add this to your app.configure
    app.use(express.session({
      secret: "kqsdjfmlksdhfhzirzeoibrzecrbzuzefcuercazeafxzeokwdfzeijfxcerig",
      store: new RedisStore({ host: 'localhost', port: 3000, client: redis })
    }));
    

提交回复
热议问题