This article will introduce to you the cookie and session in nodejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Related recommendations: "nodejs Tutorial"
I am used to using plug-ins in the framework, and recently I was reviewing the basic module of node. I can’t help but wonder: What are cookies? What is a session? What are the differences and connections between the two? Does Node.js provide corresponding modules to manage storage sessions? If no corresponding module is provided, how should we implement a module similar to Session management?
Session and Cookie are both based on the Web server and are different The cookie is stored on the client side, and the Session is stored on the server side.
When a user browses a website, the web server will store some information about the current user on the browser, and what is stored on the local web client is cookie data. In this way, the next time the user browses the same website, the web server will first check and read the local cookie information. If there is a cookie, it will determine its expiration time based on the content in the cookie, thereby returning special data to the user.
The use of cookies is very common - many websites that support personalized services mostly use cookies to identify users so that they can send content tailored to the user, such as free emails on the web interface. Another example: the “7 days no login” supported by most websites.
Specifically, the cookie mechanism uses a solution that maintains state on the client side, while the session mechanism uses a solution that maintains state on the server side. At the same time, we can also see that since the solution of maintaining state on the server side also needs to save an identity on the client side, the session mechanism may need to use the cookie mechanism to achieve the purpose of saving the identity. But it actually has other options. Orthodox cookie distribution is achieved by extending the HTTP protocol. The server adds a special line of identification to the http response header to prompt the browser to generate the corresponding cookie according to the instructions. However, pure client-side scripts such as JavaScript or VBScript can also generate cookies - document.cookie='xxx=xxx; expires=xxx'
.
Cookie is based on session
The use of cookie is automatically sent to the server in the background by the browser according to certain principles. The browser checks all stored cookies. If the declared scope of a cookie is greater than or equal to the location of the resource to be requested, the cookie can be attached to the HTTP request header to request the resource and sent to the server.
The contents of Cookie mainly include: name, value, expiration time, path and domain. The path and domain together form the scope of the cookie. If the expiration time is not set, it means that the lifetime of this cookie is during the browser session. When the browser window is closed, the cookie disappears. This type of cookie whose life span is the browser session is called a session cookie. Session cookies are generally not stored on the hard disk, but in memory. Of course, this behavior is not standardized. If an expiration time is set, the browser will save the cookies to the hard disk. If you close and open the browser again, these cookies will still be valid until the set expiration time is exceeded.
Different browsers have different processing methods for cookies stored in memory. The Session mechanism is a server-side mechanism. The server uses a structure similar to a hash table (or may actually use a hash table) to save information. When the program needs to create a Session for a client's request, the server first checks whether the client's request already contains a Session identifier (called Session id). If it does, it means that a Session has been created for this client before. , the server retrieves the Session according to the Session id and uses it (if it cannot be retrieved, it will create a new one). If the client request does not contain the Session id, a Session is created for the client and a Session associated with this Session is generated. id, the value of Session id should be a string that is neither repeated nor easy to find the regularity of its generation. This Session id will be returned to the client for storage in this response. Cookies can be used to save this Session id, so that during the interaction process the browser can automatically send this identification to the server according to the rules. Generally, the name of this cookie is similar to SESSID.
Since session is so "important", we might as well take a look at the session module:
There is a built-in session method in PHP that can be called. For example session_start
and $_SESSION
etc. However, the native Node.js does not provide any session management module, so we can implement one ourselves:
Based on the above introduction to session and cookie, it is not difficult for us to figure out the logic
(Actually, the server checks whether the session has a corresponding session id in the browser's cookie )
As shown in the figure above, the client will first request the Session, and when the server checks that the cookie in the client does not have a corresponding Session id, it will generate a new Session id for it in a certain way. If the Session id exists in the cookie and has not expired, the Session data will be returned directly.
Then according to the above process diagram and introduction, we can first create three methods for the modules we need to implement, namely start, newSession and cleanSessions. The start method mainly starts Session management, newSession mainly creates a new Session id for the client, and cleanSessions clears Session data.
This module uses a Session array to store all Sessions in the system. When a Session id exists, there is no need to create a new Session id, but directly reads and returns the Session data; when the Session id does not exist, a Session id needs to be created and the Session id is returned. The sessionid is stored in that client's cookie. The author made a simple session verification start, the code is as follows:
var start = function(req,res){ var conn = { res: res, req: req }; var cookies = {}; if(typeof conn.req.headers.cookie !== "undefined"){ //session存在时,对session进行解析,获取其中的session id conn.req.headers.cookie.split(';').forEach(function(cookie){ var parts=cookie.split('='); cookies[ parts[0].trim() ] = (parts[1] || '').trim(); }); }else{ cookies.SESSID = 0; } var SESSID = cookies.SESSID; if(typeof sessions[SESSID] !== "undefined"){ //判断服务器中是否存在该session值 session=sessions[SESSID]; if(session.expires <p> The above is a simple session verification process. The main idea is to obtain the cookie through the headers in the req object, and parse the cookie to obtain the session. id, and then determine whether the id value exists, thereby returning or generating a new session. Let's take a look at the implementation of the main method newSession: </p><pre class="brush:php;toolbar:false">function newSession(res){ var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; var SESSID = ''; for(var i = 0; i <p>Of course, the last step is to expose the entire module: </p><pre class="brush:php;toolbar:false">exports.start=start;
Application of the Session module
We can require the module in the entry file (such as app.js), call session.start in the HTTP createServer function, and store the object returned by session.start as a global object. The code is as follows:
var app=http.createServer(function(req,res){ global.sessionLib = session.start(res,req); }); //调用时 if(!sessionLib['username']){ sessionLib['username'] = 'mxc'; }
After introducing the basic module, let’s take one of the author’s projects to explain the basic usage of related plug-ins in the framework——In fact, The implementation principle is exactly the same as what is stated in this article.
const cookieSession=require('cookie-session');
(function (){ var keys=[]; for(var i=0;i<p>Judge when using: </p><pre class="brush:php;toolbar:false"> //检查登录状态 router.use((req, res, next)=>{ if(!req.session['admin_id'] && req.url!='/login'){ //没有登录且当前不是登录页(避免redirect黑洞) res.redirect('/admin/login'); }else{ next(); } });
After logging in:
req.session['admin_id']=data[0].ID;
For more programming-related knowledge, please visit: Programming Video! !
The above is the detailed content of Let's take a look at cookies and sessions in nodejs. For more information, please follow other related articles on the PHP Chinese website!