gpt4 book ai didi

javascript - NodeJS - 没有 Express 的 session 处理

转载 作者:行者123 更新时间:2023-12-02 22:27:40 25 4
gpt4 key购买 nike

我已经构建了我的应用程序,我在 NodeJS 上使用了纯 JS,它是一个单页应用程序。我没有使用 express 。

首先,用户需要登录。登录数据通过 websocket 发送到服务器,并根据 MySql-DB 检查凭据。如果正确,则会生成登录内容并将其发送回客户端并在客户端显示。

现在,当用户已经登录,然后刷新浏览器时,他会进入应用程序的初始状态,需要再次登录。

我该如何解决这个问题?

我读了很多关于 NodeJS 中 session 处理的内容,但大多数文章都包含express,这让我很难理解整个概念。

最佳答案

HTTP 本身是无状态的,因此您需要某种方式来识别用户。

传统上,这是通过 cookie 完成的。当您响应 HTTP 请求时,您会在响应 header 中包含一个 cookie。对于所有后续 HTTP 请求,客户端都会将此 Cookie 信息返回给您。

这意味着您可以发送某种 session 标识符,并且对于将来的所有请求,您可以查找 session 数据。对话有点像这样。

Client: Here's my login information, and I'd like the home page.

Server: Ok, thanks. Here's the home page. Also, remember that your session ID is 12345. Next time you ask me for something, tell me that session ID. (Logs in the database that session ID 12345 is associated with someuser.)

然后后来...

Client: I'd like this other page. You told me to tell you that my session ID is 12345.

Server: (Loads session information for 12345, sees that it's associated with someuser.) Ok, here's that other page.

您实际上如何存储所有内容取决于您。许多人使用数据库,因为他们通常已经在应用程序中使用数据库,并且可以轻松地与应用程序服务器的多个实例共享 session 数据。

关于javascript - NodeJS - 没有 Express 的 session 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59011555/

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