【问题标题】:Keep Session after node.js restartnode.js重启后保持会话
【发布时间】:2015-09-06 23:01:21
【问题描述】:

我正在尝试获取会话以将护照会话存储在 express v4 中,并且在服务器重新启动后它不会持续存在。我已经在使用connect-mongo,所以不清楚为什么目前没有持续存在。

db.js

module.exports = function(app, config) {
    var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    session = require('express-session'),
    MongoStore = require('connect-mongo')(session),
    fs = require('fs');

    mongoose.connect(config.db);

    mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
    mongoose.connection.once('open', function callback() {
        console.info('Database Connected!');
    });

    var sessionStore = new MongoStore({mongooseConnection: mongoose.connection});
    module.exports = sessionStore;
};

express.js

module.exports = function (app, config, passport, dbConnect) {
    /* #Flash messaging and sessions ------------------------------------------------- */
    app.use(cookieParser('secretStrings'));
    app.use(session({
        secret: 'secretStrings',
        resave: true,
        saveUninitialized: true,
        cookie: {
            path: '/',
            httpOnly: true,
            secure: false,
            maxAge: null
        },
        rolling: true,
        store: dbConnect
    }));
    app.use(flash());

    /* #Set up passport ------------------------------------------------- */
    // use passport session
    app.use(passport.initialize());
    app.use(passport.session());
};

Server.js

/* #Mongo --------------------------------------------------------------------- */
var db = require('./app/db')(app, config);

/* #Express Settings --------------------------------------------------------------------- */
require('./config/express')(app, config, passport, db);

我认为对此唯一合乎逻辑的解释是我以错误的顺序包含文件,因此无法保存会话?

【问题讨论】:

  • 不应该将module.exports = sessionStore; 改为return sessionStore; 在您的db.js 中吗?
  • 大声笑当然应该。当我在 express.js 而不是 db.js 中使用它时,我已经复制粘贴了它!嗯,将其添加为答案,我会接受。虽然我想知道,我是否应该删除这个问题,因为它是一个非常具体的问题。

标签: javascript node.js mongodb session


【解决方案1】:

sessionStore 需要在 db.js 中使用 returned 而不是 module.exports = sessionStore;

【讨论】:

    猜你喜欢
    • 2015-02-24
    • 2021-12-07
    • 1970-01-01
    • 2012-12-09
    • 2021-08-22
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 2011-07-14
    相关资源
    最近更新 更多