NodeJS + Express + Mongo Session storage

后端 未结 1 1935
小蘑菇
小蘑菇 2021-02-03 15:38

I am currently having a hell of time trying to store sessions in MongoDb.

I\'ve tried express-session-mongo and connect-mongodb and both give me the same \"500 internal

相关标签:
1条回答
  • 2021-02-03 16:10

    It ended being a problem of the various modules: connect-session-mongo / express-session-mongo / connect-mongo, using connect 2.0.1 and Express using connect 1.8.5.

    Apparently the dependency clash here prevented the session store modules to access the 'req.secret' property.

    To make it work I ended using the module connect-mongodb that is still using connect 1.8.5, just like Express.

    The reason I couldn't make connect-mongodb work before though was user error, I tried too hard to use copy/paste from online examples instead of my head.

    Here is the configuration code that ended up working for me with connect-mongodb:

    var Session = require('connect-mongodb');
    
    app.configure('production', function(){
      var oneWeek = 657450000;
      app.use(express.static(__dirname + '/../public', { maxAge: oneWeek }));
    
      var session = express.session({
            store: new Session({
                  url: 'mongodb://localhost:27017/test', 
                  maxAge: 300000
            }),
            secret: 'superTopSecret' 
      });
      app.use(session);
    
      app.use(mongooseAuth.middleware());
      app.use(require('./mySite').middleware());
      app.use(express.methodOverride());
      app.use(express.errorHandler());  
    });
    

    Hope this helps anyone else who runs into this issue. If you have any suggestion/improvement on this solution, I'd be glad to hear it. :)

    0 讨论(0)
提交回复
热议问题