Express中间件中的访问会话对象 [英] Access session object in Express middleware
问题描述
这是我的Express中间件堆栈:
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('./../'));
这是两条路线:
server.post('/setSession', function (req, res) {
req.session.user = 'admin';
}
server.post('/getSession', function (req, res) {
console.log(req.session.user);
}
现在,在路由处理程序中找到会话管理工作.我可以设置session.user
,它将保留在同一会话中的后续请求中,这已得到getSession
的确认.但是,中间件功能printSession
总是打印undefined
.
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
.
如何访问中间件中填充的session
对象?
How can I access the populated session
object in the middleware?
推荐答案
该程序运行正常.在我访问/setSession
之前,中间件将打印after session: undefined
.一旦我获得/setSession,它就会打印after session: admin
.只要您要测试的浏览器(而不是curl)存储并发送会话cookie,它就会按预期运行.
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);
这篇关于Express中间件中的访问会话对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!