简体   繁体   English

如何使用 express-session 检测第一个连接

[英]How to detect first connection using express-session

It must be native, am I missing something ?它必须是本地的,我错过了什么吗? I can set a counter bound to the request.session variable, although, I want a more explicit way.我可以设置一个绑定到 request.session 变量的计数器,不过,我想要一种更明确的方式。

If you want to use express-session, it does not have a built-in way to know when the session is brand new.如果您想使用 express-session,它没有内置的方式来知道会话何时是全新的。 A counter is a simple solution.计数器是一个简单的解决方案。 Or, this simple middleware implements the isNew property you asked about and avoids saving the session except the first two times it is accessed:或者,这个简单的中间件实现了您询问的isNew属性,并避免保存会话,除非前两次访问它:

app.use(session(...));

app.use((req, res, next) => {
    if (typeof req.session.isNew === "undefined") {
        req.session.isNew = true;
        req.session.save(next);
    } else if (req.session.isNew) {
        req.session.isNew = false;
        req.session.save(next);
    } else {
        next();
    }
});

// output value of isNew (only here for demonstration purposes)
app.use((req, res, next) => {
   console.log(req.session.isNew);
   next();
});

I should add that this also attempts to avoid race conditions by immediately saving the session (to the session store) as soon as it is updated so if two requests arrive close in time and the first one goes asynchronous allowing the second one to start, then the second one will still see the accurate value for req.session.isNew .我应该补充一点,这也试图通过在更新后立即保存会话(到会话存储)来避免竞争条件,所以如果两个请求及时到达并且第一个请求异步允许第二个请求开始,那么第二个仍然会看到req.session.isNew的准确值。

req.session.isNew

session is always accessed through a request object, also there is a boolean field called isNew. session 总是通过请求对象访问,还有一个名为 isNew 的布尔字段。

Edit: This is part of cookie-session which is a session middleware.编辑:这是 cookie-session 的一部分,它是一个会话中间件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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