本文介绍了如何清除在节点js中清除浏览器cookie的req.session?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将"express":〜4.14.0" express-session 一起使用来保存用户名.用户登录后,我会将用户名保存在 req.session.authorizedUser = username 中,以将其显示在应用程序标题中.

I am using "express": "~4.14.0" with express-session for saving username. Once the user is logged in, I will save the user name in req.session.authorizedUser = username to display it in the application header.

清除浏览器历史记录或关闭浏览器后,我想清除会话.

When either the browser history is cleared or the browser is closed, I want to clear the session.

执行这两项操作中的任何操作时,如果有任何清除会话的方法,请提出建议.我已经尝试为会话cookie设置 maxAge 选项,如下所示,但是它不能反映出很好的效果:

Please suggest me if there is any way to clear the session when doing any of these two operations. I have tried setting the maxAge option for session cookies, as shown below, but it doesn't reflects good:

app.use(session({
    secret: "key test",
    resave: false,
    saveUninitialized: true,
    cookie: { secure: !true, path: '/', httpOnly: true, maxAge: null}
}));

推荐答案

由于浏览器删除cookie时(无论出于何种原因)不会通知服务器,因此无法在服务器端完全告诉 会话是否仍然有效.

Since a browser doesn't notify a server when it deletes cookies (for whatever reason), there's no way of telling purely on the server side if a session should still be valid or not.

这就是为什么大多数会话存储都具有到期机制的原因,该机制会在特定时间(通常与 maxAge 相关联)之后删除空闲会话.

That's why most session stores have an expiry mechanism that will delete idle sessions after a specific amount of time (which is usually tied to maxAge).

例如, connect-mongo 会话存储使用MongoDB的TTL功能从数据库中删除过期的会话.

For instance, the connect-mongo session store uses MongoDB's TTL feature to remove expired sessions from the database.

除了占用一些存储空间外,空闲会话也不是问题.当用户再次登录时,将为他们创建一个新会话,而旧会话最终将过期并从存储中删除.

Apart from taking up a bit of storage space, idle sessions aren't a problem, though. When the user logs in again, a new session will be created for them, and the old one will eventually expire and be removed from storage.

这篇关于如何清除在节点js中清除浏览器cookie的req.session?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 16:35
查看更多