更新/刷新Express会话 [英] Renewing/Refreshing Express Session
问题描述
在我的应用中,如果用户未登录,我将限制对某些操作和页面的访问.我有:
In my app I restrict some access to some actions and pages if a user is not logged in. I have:
var restrict = function(req, res, next) {
if (!req.user) {
console.log("USER isn't logged in.")
return res.status(403).send('Access or action denied, please log in');
}
next();
}
app.get('/stocks', restrict, MainHandler.findAllStocksFromUser);
app.get('/stocks/:id', MainHandler.findStockByIdAndDates);
app.put('/stocks/:id/stockActions', restrict, MainHandler.handleStockAction);
从本质上讲,我每次客户端向服务器发出请求时都试图刷新会话,以使服务器不会注销用户/在不应该注销会话时销毁该会话.为了进行测试,我希望会话过期/如果在20秒内没有用户向服务器发出请求,则该用户将被注销.我有:
I'm essentially trying to refresh a session everytime the client makes a request to the server so that the server doesn't logout the user/destroy the session when it shouldn't. For testing, I want the session to expire/the user to be logged out if 20 seconds go by without the user making an requests to the server. I have:
app.use(session({secret: 'secret', saveUninitialized: true, resave: true, expires: new Date(Date.now() + (20000))}));
然后我尝试使用中间件在每次使用者发出请求时刷新到期日期:
Then I try to use middleware to refresh the expiration date every time the use makes a request:
// Session-persisted message middleware
app.use(function(req, res, next){
req.session.cookie.expires = new Date(Date.now() + 20000);
next();
});
但是,如果我从客户端登录并单击以引起对服务器的请求,尽管尝试刷新"中间件中的会话,但20秒后仍会在客户端上出现登录错误.我也尝试过使用与中间件相同的策略使用maxAge.有任何想法吗?谢谢!
But if I log in from the client, and click around, causing requests to the server, I still get the log-in error on the client after 20 seconds, despite trying to "refresh" the session in the middleware. I have also tried using maxAge using the same strategy with the middleware. Any ideas? Thanks!
推荐答案
您可以尝试如下定义会话
You can try define your session as follows
app.use (
session ({
secret: "secret",
saveUninitialized: true,
resave: true,
cookie: {
expires: 20 * 1000
}
})
);
,然后使用
req.session.touch()
或者您可以将会话定义为
or you could define your session as
app.use (
session ({
secret: "secret",
saveUninitialized: false,
resave: true,
rolling: true,
cookie: {
expires: 20 * 1000
}
})
);
,它将自动更新会话,并且只有当它对于expires变量中的值处于空闲状态时,它才会过期
and it will renew the session automatically and it will only expire when it has been idle for the value in the expires variable
这篇关于更新/刷新Express会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!