会话如何在 Express.js 和 Node.js 中工作? [英] How do sessions work in Express.js with Node.js?

查看:34
本文介绍了会话如何在 Express.js 和 Node.js 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Express.js,会话非常简单.我很好奇它们实际上是如何工作的.

Using Express.js, sessions are dead simple. I'm curious how they actually work though.

它是否在客户端存储了一些 cookie?如果是这样,我在哪里可以找到那个 cookie?如果需要,我该如何解码?

Does it store some cookie on the client? If so, where can I find that cookie? If required, how do I decode it?

我基本上希望能够查看用户是否已登录,即使该用户当时实际上并未在该网站上(例如,当您在其他网站上时,facebook 如何知道您已登录).但我想明白我应该首先了解会话是如何工作的.

I basically want to be able to see if a user is logged in, even when the user is not actually on the site at the time (like how facebook knows you're logged in when you're on other sites). But I suppose to understand that I should first understand how sessions work.

推荐答案

我从未使用过 Express.js,尽管根据 他们的文档 听起来像:

I have never used Express.js, although according to their documentation on the subject it sounds like:

  • Cookie 存储在客户端上,带有一个密钥(服务器将使用它来检索会话数据)和一个哈希值(服务器将使用它来确保 cookie 数据未被篡改,因此,如果您尝试更改值,cookie 将无效)

  • Cookies are stored on the client, with a key (which the server will use to retrieve the session data) and a hash (which the server will use to make sure the cookie data hasn't been tampered with, so if you try and change a value the cookie will be invalid)

会话数据,而不是某些框架(例如 Play 框架!)保存在服务器上,因此 cookie 更像是会话的占位符,而不是实际会话数据的持有者.

The session data, as opposed to some frameworks (e.g. Play Framework!) is held on the server, so the cookie is more like a placeholder for the session than a holder of actual session data.

这里,看起来服务器上的这个会话数据是默认情况下保存在内存中,尽管可以将其更改为实现适当 API 的任何存储形式.

From here, it looks like this session data on the server is by default held in memory, although that could be altered to whatever storage form implements the appropriate API.

因此,如果您想在没有特定 req 请求对象的情况下检查事物,就像您说的那样,您只需要访问相同的存储.在第一个文档页面的底部,它详细说明了存储需要实现的必需方法,所以如果你熟悉你的存储 API,也许你可以执行一个 .getAll() 如果是这样的话存在,并遍历会话数据并读取您想要的任何值.

So if you want to check things without a specific req request object, like you said, you need to just access that same storage. On the bottom of the first documentation page, it details required methods the storage needs to implement, so if you're familiar with your storage API, maybe you could execute a .getAll() if something like that exists, and loop through the session data and read whatever values you want.

这篇关于会话如何在 Express.js 和 Node.js 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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