I have an Express application with some routes, only two of them need to support sessions.
I read everywhere that the middleware definition (app.use(express.session({...) applies only to the routes that comes after it, so I created this sample:
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.get('/path1', function (req, res) {
res.send('text response');
});
app.use(express.cookieParser());
app.use(express.session({
secret: 'secret',
cookie: { maxAge: new Date(Date.now() + 2 * 60 * 1000) }
}));
app.get('/path2', function (req, res) {
res.session.test = { "test": "test" };
res.send('text response');
});
app.listen(8088);
But this doesn't work: in /path2 res.session is undefined.
If I move the session middleware definition up - everything works, but I see that sessions are being create when calling /path1 (this is what I want to avoid)
Can someone explain how a single application can use session in only some of the routes.
Thanks!
///// UPDATE //////
After more digging - I figured it out:
Don't use: app.use(express.session({ ... }));
Instead - define the following:
var sessionMiddleware = express.session({
//session configurations
});
function sessionHandler(req, res, next) { sessionMiddleware(req, res, next); }
Then apply the handler on the specific route/s that need session support:
app.get('/path_that_need_session', sessionHandler, function (req, res) {
/* Do somthing with req.session */
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…