nodejs - build a movie blog (session persistent session)

write picture description here
As we all know, the communication protocol between the client and the server generally adopts the stateless HTPP/HTTPS protocol, so a mechanism is needed to record the session content between the client and the server - (cookie+session), for For different clients, the corresponding sessions are independent.


cookie: used to record the user's identity on the client side;
session: used to record the user's information on the server side to determine the identity.
write picture description here

在session出现以前,服务器端和客户端都是通过cookie保存用户信息,每次http请求,客户端都会带给服务器当前域下的cookie值,浏览器收到客户端传来的cookie或者加密以后的cookie后,对其进行解析,辨识客户端;解析后的用户数据采用键值对的形式存储于客户端。
session存储于服务器端与cookie配合使用。当服务器端收到客户端http请求时,首先检查其是否有session标识(一般为sessionid),若有,则说明服务器已经为该客户端创建过session,根据session标识找到其对应的session即可;若无session标识,服务器就会为客户端创建一个session啦!并且生成一个sessionid,且这个sessionid还是唯一的,很难找到回来的字符串喔,以防被伪造!!!
看上图就知道啦,生成的seeionID在响应http请求时传递给客户端,一般放在cookie中。
一般情况下,session是被存储在服务器的内存中的,但是当我们的服务器进程被停止,内存中的session就会被清空啦!

write picture description here
But, by configuring the session feature, it can be stored in the hard disk, so that every time the server restarts, it can be read from the hard disk and used again! - This is the so-called session persistence! ! !
There are several common ways for session persistence: see the figure above, cookie, memory, redis, mongoDB

write picture description here
The development of this project is based on the Express framework. In Express 3.X, Express is based on the development of the connect module; Express's cookieParse is the middleware for cookie parsing; Express's session is used to provide session support; in Express's seeion The secret can be configured here to prevent cookie tampering; the key value is the name of the cookie; maxAge sets the lifetime of the cookie, and store sets the mongoStore instance to store session information.
write picture description here
The parsing of seeions in Express relies on CookieParser. First read the encrypted connectionsid from the cookie, and then parse it into the corresponding sessionid through cookieParser; this seeionid is placed in the request session. As can be seen from the express session diagram, CookieParser must be placed in front of the seeion middleware. When using the session middleware, the store object is first read to read the current session data, so when multiple requests are executed concurrently, they obtain the same session data. When each request executes res.end(), the session will be saved again.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325926563&siteId=291194637