Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
804 views
in Technique[技术] by (71.8m points)

node.js - 'session' is undefined when using express / redis for session store

I'm trying to use redis for sessions in my express app.

I do the following:

var express = require('express');
var RedisStore = require('connect-redis')(express);

app.configure('development', function(){     
    app.use(express.session({ secret: "password", 
                            store: new RedisStore({
                                          host: "127.0.0.1",
                                          port: "6379",
                                          db: "mydb"
                                        })  
          }));

Later on, in my app, if i do something like:

var whatever = req.session.someProperty;

I get:

Cannot read property 'someProperty' of undefined

This indicates that req.session is undefined (I can see this from a console.log entry in my config section)

I've definitely got redis running, and can see my app connects to it initially (using redis-cli monitor)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Sessions won't work unless you have these 3 in this order:

app.use(express.cookieParser());
app.use(express.session());
app.use(app.router);

I'm not sure if router is mandatory to use sessions, but it breaks them if it's placed before them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...