[英]How to hook into express session creation event
How can I tell when express creates a new session? 如何确定Express创建新会话的时间? I'm using a mongodb session store. 我正在使用mongodb会话存储。
I'm having an issue with extra sessions being created, and want to narrow down on the problem by tracking which urls requests are triggering new sessions to be created. 我在创建额外的会话时遇到问题,并且想通过跟踪哪些url请求触发要创建的新会话来缩小问题的范围。
You can hook into the genid
callback. 您可以连接到genid
回调。 By default express-session
generates its own session IDs. 默认情况下, express-session
生成自己的会话ID。
But you can generate the session ID yourself by specifying a genid
callback. 但是您可以通过指定一个genid
回调自己生成会话ID。 Within this callback you can log that a new session is being created (and then return a unique session ID). 在此回调中,您可以记录正在创建新的会话(然后返回唯一的会话ID)。
Here is an example, adapted from the express-session
README: 这是一个改编自express-session
自述文件的示例:
app.use(session({
genid: function(req) {
console.log('New session was created');
return genuuid(); // generate a UUID somehow and return it
},
secret: 'keyboard cat'
}));
This is what I ended up doing. 这就是我最终要做的。
app.use(function(req, res, next) {
if (!req.session.returning) {
// session was just created
req.session.returning = true
} else {
// old session
}
next()
})
The answer by Nate is fine. 内特的答案很好。 I'm answering because of 2 additions I'd like to make. 我要回答,是因为我想补充2个内容。
const uid = require('uid-safe').sync;
//...
genid: function(req) {
console.log('New session was created');
// do what you want to do here!
return uid(24); // <-- the way express-session generates it
},
async
function for genid. 请注意,您不能对Genid使用async
功能。 Express-session calls this function without await
, so that would get a promise instead of the uid. Express-session在不await
情况下调用此函数,因此将获得一个Promise而不是uid。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.