NodeJS + ExpressJS + RedisStore会话未定义 [英] NodeJS + ExpressJS + RedisStore Session is undefined

查看:73
本文介绍了NodeJS + ExpressJS + RedisStore会话未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've gone through many questions with the same issue, but none of the various solutions have helped. I'm using Redis to store session in a clustered NodeJS+ExpressJS application, but the session is always undefined. Here's my Express setup:

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

Even without using the Redis store, I'm getting the following error: TypeError: Cannot read property 'user' of undefined

推荐答案

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

You'll have to instantiate the sessions before the routes.

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

这篇关于NodeJS + ExpressJS + RedisStore会话未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆