gpt4 book ai didi

javascript - 如何从浏览器检查 Node session cookie 过期时间

转载 作者:太空宇宙 更新时间:2023-11-04 01:06:34 27 4
gpt4 key购买 nike

我们使用 Node + Connect 来管理应用程序的 session ,该应用程序是使用 Backbone.js 构建的单页应用程序 (SPA)。我正在尝试编写一些代码来从客户端检查 session 是否仍然有效。我知道我可以在 Node 本身中完成此操作,但由于这是一个 SPA,我需要能够完全在客户端完成此操作。

我的第一个想法是使用 jQuery 读取 connect.sid cookie,如果它不存在,则意味着 session 已过期。不幸的是,该 session cookie 受到 HttpOnly 标志的保护,这是有充分理由的。我不想禁用它。

我的第二个想法是在每次写入 connect.sid cookie 时写入一个第二个并行 cookie。第二个 cookie 仅存储 session cookie 的过期日期,并将 HttpOnly 设置为 false,以便客户端可以读取它。

So my question is, how do I go about writing that second cookie, or is there a better solution for being able to detect session expiration status from the browser?

I know how to write cookies with Node, but I'm not sure where to put the code so that it will fire every time that Connect writes the main connect.sid session cookie. Additionally, I would like to be to read the expire date of the session cookie so that I can write it in my parallel cookie.

更新:需要明确的是,我不想读取 session 的到期日期。我知道JS无法访问cookie的过期日期。我只是想看看 cookie 是否存在,因为它只有在有效时才会存在,因此它的不存在对我来说就足够了。

最佳答案

在评论中澄清后更新

在 session 中间件旁边添加另一个中间件。下面的摘录假设使用express,但如果您使用不带express的连接,您应该能够进行相应的解释。

app.use(connect.session(sessionOptions));
app.use(function (req, res, next) {
res.cookie("sessionIsAlive", "1", {
//just make sure this matches your expiration time of the real session cookie
expires: new Date(Date.now() + 900000),
httpOnly: false
});
next();
});

然后您可以通过浏览器中的 javascript 检查该文件是否存在。仅供引用,connect 会在每次响应时写入一个带有更新过期时间的新 cookie。这就是“N 分钟不活动后过期”行为的实现方式。

关于javascript - 如何从浏览器检查 Node session cookie 过期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22334208/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com