Express.js和connect-mongo会话持续时间 [英] Express.js and connect-mongo session duration

查看:239
本文介绍了Express.js和connect-mongo会话持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用express.session与connect-mongo来存储用户会话。
我将cookie maxAge设置为从现在开始的2周,但我想要的是,如果用户在这两个星期内活动,会话延长到另外2周,所以当他不活动2周,他的会话删除(cookie和mongo中的会话)。
但是问题是,当他访问页面时,会话在MongoDB中更新,但cookie将在2周后过期,并且不会更改它的过期。
这是我的代码:

  app.use(express.session({
secret:'superSecretKey ',
cookie:{maxAge:3600000 * 24 * 14},
store:new MongoStore({
mongoose_connection:mongoose.connections [0],
db:'myDb'
})
}));

如何实现我想要的?
谢谢!

解决方案

我终于解决了,你必须使用中间件更新会话中的任何数据该cookie重新发送,如下所示:

  app.use(function(req,res,next){
req.session._garbage = Date();
req.session.touch();
next();
});

这样,maxAge将在每次请求到应用程序时都更新cookie和会话。 / p>

I use express.session with connect-mongo to store user sessions. I set cookie maxAge to 2 weeks from now, but what I want is that if the user is active within those 2 weeks, the session extends to another 2 weeks, so that when he is inactive for 2 weeks his session gets deleted (both the cookie and the session in mongo). But the problem is that the session gets updated in MongoDB when he visits a page, but the cookie will expire in 2 weeks and won't change it's 'expires'. This is my code:

app.use(express.session({
  secret: 'superSecretKey',
  cookie: {maxAge: 3600000*24*14},
  store: new MongoStore({
    mongoose_connection: mongoose.connections[0],
    db: 'myDb'
  })
}));

How can I achieve what I want? Thanks!

解决方案

I finally solved it, you have to use a middleware to update any data in the session so that the cookie gets resend, just like this:

app.use(function(req, res, next) {
  req.session._garbage = Date();
  req.session.touch();
  next();
});

This way maxAge will update both on the cookie and on the session on every request to the app.

这篇关于Express.js和connect-mongo会话持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆