简体   繁体   中英

NodeJS - Session handling WITHOUT express

I have built my app, I used plain JS on NodeJS and it is a single-page app. I didn't use express.

First the user needs to log in. The login-data is sent via websocket to the server and there the credentials are checked against a MySql-DB. If they are correct, the loggedIn-content is generated and sent back to the client, where it is displayed.

Now when a user is already logged in, and then refreshes the browser, he lands on the initial state of the app, and needs to log in again.

how can I fix this?

I read a lot about session-handling in NodeJS, but most articles include express, which confuses me to understand this whole concept.

For plain nodejs server you can try https://www.npmjs.com/package/node-session library. At first sign it suitable for you. But it is not supported for a long time.

HTTP itself is stateless, so you need some sort of way to identify the user.

Traditionally, this is done via cookies. When you respond to an HTTP request, you include a cookie in your response headers. For all subsequent HTTP requests, the client will include this cookie information back to you.

This means that you can send some sort of session identifier, and for all future requests you can look up the session data. The conversation goes a bit like this.

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.)

Then later...

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.

How you actually do the storage of all that is up to you. Many folks use databases, since they're often already using them for the application and it makes it easy to share session data with multiple instances of the application server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM