1

I've been having problems trying to access stored session values! Once I've set the values and try access them from a new route, I get undefined! So basically I've got a login (POST) and in that request I set the session data, and then I have a show user details (POST) where I try and access the session data I've just stored.

Setup

// Setup express and needed modules #############################################
    var express = require('express'),
        session = require('express-session'),
        cookieParser = require('cookie-parser'),
        redis = require("redis"),
        redisStore = require('connect-redis')(session),
        bodyParser = require('body-parser');

var client = redis.createClient(), //CREATE REDIS CLIENT
    app = express();

// Setup app
app.use(cookieParser('yoursecretcode'));
app.use(session(
    {
        secret: 'x', 
        store: new redisStore({
            port: 6379, 
            client: client 
        }),
        saveUninitialized: true, // don't create session until something stored,
        resave: false // don't save session if unmodified
    }
));
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.set('trust proxy', 1) // trust first proxy

So as you've seen my setup, you know I'm using express sessions and Redis. Below is where I'm setting the session values! If I print out the session values here it works, but then If I try and access the session data in another route it returns undefined.

Routes

I send a http post request and set the session data:

router.route('/login/').post(function(req, res) {
        req.session.userId = req.body.uId;
        req.session.name = req.body.uName;
        // THIS PRINTS OUT IF I TRY AND ACCESS THE SESSION DATA HERE
        console.log("THIS PRINTS OUT --> " + req.session.name);
 });

So now that the session values have been set, I can go access them right, no, I get undefined each time I try and log them out.

router.route('/user/printoutuserdetails').post(function(req, res) {
        // THESE RETURN UNDEFINED
        console.log(req.session.userId);
        console.log(req.session.uName);
        console.log("THIS PRINTS OUT --> " + req.session.name);
 });

Does anyone have any idea what's happening? I've tried everything and looked everywhere and can't seem to find a way to get it to work!

Solved:

The reason this wasn't was because you're not suppose to use sessions when using a RESTFUL api.

Community
  • 1
  • 1
James111
  • 15,378
  • 15
  • 78
  • 121

0 Answers0