Nodejs's Cookie and session (i)

Source: Internet
Author: User
Tags session id send cookies hasownproperty

Nodejs's Cookie and session (i)

A: Cookies
HTTP is a stateless protocol, how do you associate the last request with the data of the next request each time the client makes a request and the next request does not get the data of the last request?
such as login to the official website, and then switch to other pages, then the other page is how to know that the user has logged in? So this can be used to determine the value of the cookie.

Cookie it is a protocol implemented by the browser and the server in collaboration. Then the cookie is divided into the following steps:
1. Server-side sends a cookie to the client.
2. The browser saves the cookie.
3. Each request will then be sent to the server side of the cookie.

1.1 Server-Side Send cookies

The server sends a cookie to the client via an HTTP response message. The Cookie,cookie format that is set to the client in Set-cookie is as follows:
Set-cookie:name=value; max-age=60; path=/; domain=.domain.com; Expires=sun, may 2018 05:44:24 GMT; HttpOnly, secure;

As shown

Where Name=value is required, others are optional and the cookie is mainly composed of the following:

Name : a uniquely identifying cookie.
Value : The values of the strings stored in the cookie.
Domain : Cookies are valid for that domain,
Path : represents the path that this cookie affects, and the browser sends a cookie to the matching path in the specified domain based on this configuration.
Expires: expiration time, which indicates when the cookie expires, and if not set, the browser will delete all cookies when the page is closed, but we can also set the expiration time ourselves.
Note: If the time set on the client and server side is inconsistent, the use of expires will be biased.
max-age: used to tell the browser how long the cookie expires (in seconds), in general, max-age priority is higher than expires.
HttpOnly: tell the browser not to allow the script Document.cookie to change the value, this value is not visible in document.cookie, but the HTTP request will carry this cookie,
Note: This value is not desirable in the script, but it exists as a file in the browser installation directory, which is typically set on the server side.
Secure : security flag, when specified, when secure is true, is invalid in HTTP and valid in HTTPS, indicating that the cookie created can only be passed to the server by the browser on the HTTPS connection for session verification. If an HTTP connection does not pass this information, it is generally not heard.

The server-side settings cookie code is as follows:

Const EXPRESS = require (' Express '= Express (); App.listen (3001, () = {  console.log (' Port Listen 3001 ');}); App.get ('/', (req, res) = {  res.setheader (' status ', ' OK ');  Res.setheader (' Set-cookie ', ' isvisit=1;domain=/;p ath=/;max-age=60*1000 ');  Res.send (' welcome you ~ ') ;

Directly set Set-cookie is too primitive, we can do the following encapsulation of the cookie setup process;

Const EXPRESS = require (' Express '); Const app=Express (); App.listen (3001, () ={Console.log (' Port Listen 3001 ');}); Const Serilize=function(name, value, options) {if(!name) {    Throw NewERRPR (' cookie must has name '); }  varRETs = []; Value= (Value!==NULL&& value!== undefined)? Value.tostring (): "; Options= Options | | {}; Rets.push (encodeURIComponent (name)+ "=" +encodeURIComponent (value)); if(Options.domain) {Rets.push (' domain= ' +Options.domain); }  if(Options.path) {Rets.push (' Path= ' +Options.path); }  if(options.expires) {Rets.push (' expires= ' +options.expires.toGMTString ()); }  if(Options.maxage &&typeofOptions.maxage = = = ' Number ') {Rets.push (' Max-age= ' +options.maxage); }  if(options.httponly) {Rets.push (' HttpOnly '); }  if(options.secure) {Rets.push (' Secure '); }  returnRets.join ('; '));}; App.get ('/', (req, res) ={Res.setheader (' Status ', ' OK '); Res.setheader (' Set-cookie ', serilize (' Isvisit ', ' 1 ')); Res.send (' Welcome you ~ ');});

1.2 Server-side parsing cookies
Cookies can have different domains and paths, so for the same name value, it can be duplicated in different domains under different paths, and the browser will prioritize in the order in which it best matches the URL or page address of the current request.
The server-side parsing code is as follows:

Const PARSE =function(str) {if(!str) {    return; } Const Dec=decodeuricomponent; varcookies = {}; Const RETs= Str.split (/\s*;\s*/g); Rets.foreach ((R)={Const POS= R.indexof (' = ')); Const name= pos >-1? Dec (r.substr (0, POS))    : R; Const Val= pos >-1? Dec (R.SUBSTR (pos + 1)):NULL; //just need to get the most matching one.    if(!Cookies.hasownproperty (name)) {Cookies[name]=Val;  }  }); returncookies;};

So the entire code looks like this:

Const EXPRESS = require (' Express '); Const app=Express (); App.listen (3001, () ={Console.log (' Port Listen 3001 ');}); Const Serilize=function(name, value, options) {if(!name) {    Throw NewERRPR (' cookie must has name '); }  varRETs = []; Value= (Value!==NULL&& value!== undefined)? Value.tostring (): "; Options= Options | | {}; Rets.push (encodeURIComponent (name)+ "=" +encodeURIComponent (value)); if(Options.domain) {Rets.push (' domain= ' +Options.domain); }  if(Options.path) {Rets.push (' Path= ' +Options.path); }  if(options.expires) {Rets.push (' expires= ' +options.expires.toGMTString ()); }  if(Options.maxage &&typeofOptions.maxage = = = ' Number ') {Rets.push (' Max-age= ' +options.maxage); }  if(options.httponly) {Rets.push (' HttpOnly '); }  if(options.secure) {Rets.push (' Secure '); }  returnRets.join ('; '));}; Const Parse=function(str) {if(!str) {    return; } Const Dec=decodeuricomponent; varcookies = {}; Const RETs= Str.split (/\s*;\s*/g); Rets.foreach ((R)={Const POS= R.indexof (' = ')); Const name= pos >-1? Dec (r.substr (0, POS))    : R; Const Val= pos >-1? Dec (R.SUBSTR (pos + 1)):NULL; //just need to get the most matching one.    if(!Cookies.hasownproperty (name)) {Cookies[name]=Val;  }  }); returncookies;}; App.get ('/', (req, res) ={Res.setheader (' Status ', ' OK '); Res.setheader (' Set-cookie ', serilize (' Isvisit ', ' 1 ')); Res.send (' Welcome you ~ '); Console.log (Parse (' Isvisit=1 '));});

After running on the command line, you can see the print out cookie information key value pair, as follows:

Cookies in the 1.3 Express

The cookie used in EXPRESS4 uses the Cookie-parser module, which uses the following code:

 Const EXPRESS = require (' Express '  = require (' Cookie-parser '  = Express (); App.listen (, () => {Console.log ( ' port listen ' );}); App.use (Cookieparser ()); App.get ( '/', (req, res) => { if   (Req.cookies.isVisit) {console.log (req.cookies);  Res.send ( ' welcome again '  else   { //  cookie set expiration time is 10 minutes  res.cookie (' Isvisit ', 1, {Maxage:60*1000});  Res.send ( ' welcome you ~ ' 

Two: Session

Cookies are easy to operate, but the use of cookies is not secure, and all the data in the cookie can be modified at the client, the data is easily falsified, so some important data cannot be placed in the cookie, and the cookie has a disadvantage that it cannot store too much data. To solve these problems, the session is created, and the data in the session is maintained on the server side.

2.1 User and data mapping based on cookies
It is not advisable to put the data in a cookie, but we can place the password in a cookie, such as a cookie that will be put into a sessionid, and the SessionID will be generated from the server side.
Mapping relationship, if the SessionID is tampered with, then it will not be mapped with the server-side data, so security is better, and the duration of the session is generally relatively short, is generally set is
20 minutes, the server will delete the data if there is no interaction between the client and the server within 20 minutes.

The principle of the session is carried out through a SessionID, SessionID is placed in the client's cookie, when the request arrives, the server checks whether the SessionID stored in the cookie is there,
And the server side of the session data map, to save and modify, that is, when we browse a Web page, the server will randomly generate a 1024-strong string, and then there is
In the SessionID field of the cookie, the cookie will have the SessionID field when we visit the next time.

Express in Express-session module

In express operation session can use express-session This module, the main method is the session (options), options include the optional parameters are:
Name : Save the field names of the session. Default is Connect.sid
Store : The session is stored in memory by default.
Secret: by setting the secret string, the hash value is computed and placed in a cookie to make the resulting signedcookie tamper-proof.
Cookies: Sets the options for the cookie that holds the session ID, which defaults to (default: {path: '/', Httponly:true, Secure:false, maxage:null})
GenID: When a new session_id is generated, the function used by default UID2 this NPM package.
rolling: Each request is reset to a cookie, which defaults to false.
Resave: The session value is saved even if the session is not modified, and the default is True

2.2 Storing session in memory
The following code:

Const EXPRESS = require (' Express '); Const session= Require (' express-session '); Const app=Express (); App.listen (3002, () ={Console.log (' Port Listen 3002 ');}); App.use (Session ({secret:' Somesecrettoken ', Cookie: {maxAge:1*60*1000}//1 minutes}); App.get ('/', (req, res) = {  /*Check the Isvisit field in the session*/  if(req.session.isVisit) {res.send (' Welcome to you again '); } Else{req.session.isVisit=true; Res.send (' Welcome to your first visit '); }});

Nodejs's Cookie and session (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.