kuba12
kuba12

Reputation: 265

How to make session variables available after redirecting in Node.js

I've got a problem. I set a session and I created this object:

req.session.userId = user.id

But when I'm redirecting to the other page this userId object is undefined there. I've reaad that it is caused by redirecting. Do you know how can I make my req.session.userId value available after redirecting?

Upvotes: 0

Views: 4176

Answers (1)

Mudaser Ali
Mudaser Ali

Reputation: 4339

You can create a session as follow:-

package.json

{
  "name": "server",
  "version": "0.0.0",
  "description": "it is a server",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "express": "~4.0.0",
    "body-parser": "~1.0.1",
    "express-session": "^1.0.2",
    "connect": "^2.13.0",
    "method-override": "~1.0.0"
  },
  "author": "SM@K",
  "license": "ISC"
}

index.js

var express = require('express');

var session = require('express-session');
var MemoryStore = require('connect').session.MemoryStore
// create our app
var app = express();

app.use(session({
    secret: "secret",
    store: new MemoryStore({reapInterval: 60000 * 10})
}));


app.get('/', function(req, res) {
    req.session.from_session = 10;
    res.redirect('/session');

});

app.get('/session', function(req, res) {
    res.send("Comming From Session: " + req.session.from_session);
});

app.get('/session-test', function(req, res) {
    res.send("Test Session: " + req.session.from_session);
});

app.listen(3001);
console.log('listen 3001');

Upvotes: 2

Related Questions