简体   繁体   中英

Access session object in Express middleware

This is my Express middleware stack:

var server = express()
    .use(express.cookieParser())
    .use(express.session({secret: 'Secret'}))
    .use(express.bodyParser())
    .use(function printSession(req, res, next) {
        console.log(req.session.user);
        next();
    })
    .use(express.static('./../'));

and here are two routes:

server.post('/setSession', function (req, res) {
    req.session.user = 'admin';
}

server.post('/getSession', function (req, res) {
    console.log(req.session.user);
}

Now the session management in the route handlers work find. I can set session.user and it will persist for the subsequent requests in the same session, as confirmed by getSession . However, the middleware function printSession always prints undefined .

How can I access the populated session object in the middleware?

This program works fine. Before I access /setSession , the middleware prints after session: undefined . Once I GET /setSession, it prints after session: admin . As long as the browser you are testing with (not curl) stores and sends the session cookies, this will work as expected.

var express = require('express');
var server = express();
server.use(express.cookieParser());
server.use(express.session({secret: 'SEKRET'}));
server.use(function (q,r,n) {console.log('after session:', q.session.user);n();});
server.get('/', function (q,r,n) {r.send("you got slashed");});
server.get('/setSession', function (req, res) {
  console.log("logging admin in via /setSession");
  req.session.user = 'admin';
  res.send("admin logged in");
});
server.listen(3000);

There must be something wrong with your settings. The following example, that is very similar to your code but uses GET instead POST , works fine for me

app.configure(function(){
  // ...
  app.use(express.cookieParser('your secret here'));
  app.use(express.session());

  app.use(function(req, res, next) {
    console.log(req.session.user + ' from middleware');
    next();
  });

  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

and

app.get('/getSession', function(req, res) {
  console.log(req.session.user);
  res.send('awesome');
});

app.get('/setSession', function(req, res) {
  req.session.user = 'admin';
  res.send('done');
});

Now when you do the following everything works as expected

  1. GET /getSession => undefined from middleware, undefined
  2. GET /setSession => undefined from middleware
  3. GET /getSession => admin from middleware, admin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM