NodeJS + ExpressJS + RedisStore会话未定义

时间:2013-12-23 23:44:42

标签: node.js session express redis

我在同一个问题上经历了很多问题,但各种解决方案都没有帮助。我正在使用Redis在集群NodeJS + ExpressJS应用程序中存储会话,但会话始终未定义。这是我的快速设置:

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

1 个答案:

答案 0 :(得分:2)

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

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);
    }
});