小编典典

NodeJS + ExpressJS + RedisStore会话未定义

redis

我曾就同一问题经历过许多问题,但各种解决方案都无济于事。我正在使用Redis将会话存储在群集的NodeJS +
ExpressJS应用程序中,但是该会话始终是未定义的。这是我的Express设置:

var express = require('express'),
    RedisStore = require('connect-redis')(express),
    Config = require('./config/config'),
    cluster = require("cluster"),
    QueryManager = require('./service/query_manager'),
    app = express();



// --- Index --- //
function renderSplash(req, res) {
    res.render(...);
}
function renderIndex(req, res) {
    res.render(...);
}

app.get('/', function(req, res) {
    if(req.session.user === null) {
        renderSplash(req, res);
    } else {
        renderIndex(req, res);
    }
});

// --- Configuration ---//
//EJS
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
app.set('views', __dirname + '/public');

app.configure(function() {
    //Session
    app.use(express.cookieParser());
    app.use(express.session({
        store: new RedisStore({
            host: Config.redis.host,
            port: Config.redis.port
        }),
        secret: 'Its a secret.',
        cookie: { secure: true }
    }));

    app.use(validateRequest); //Ensures we're at www. to hit the LB
    app.use(express.static(__dirname+'/public'));
    app.use(express.compress);
    app.use(app.router);
});

即使不使用Redis存储,我也会收到以下错误: TypeError: Cannot read property 'user' of undefined


阅读 386

收藏
2020-06-20

共1个答案

小编典典

您必须在路由之前实例化会话。

var express = require('express'),
    RedisStore = require('connect-redis')(express),
    Config = require('./config/config'),
    cluster = require("cluster"),
    QueryManager = require('./service/query_manager'),
    app = express();

app.use(express.cookieParser());
app.use(express.session({
    store: new RedisStore({
        host: Config.redis.host,
        port: Config.redis.port
    }),
    secret: 'Its a secret.',
    cookie: { secure: true }
}));

// --- Index --- //
function renderSplash(req, res) {
    res.render(...);
}
function renderIndex(req, res) {
    res.render(...);
}

app.get('/', function(req, res) {
    if(req.session.user === null) {
        renderSplash(req, res);
    } else {
        renderIndex(req, res);
    }
});
2020-06-20