The session in node. JS, don't feel simple.

Source: Internet
Author: User
Tags session id set cookie

This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph of the statement, and in the article page obvious location to the original link, blog address is http://www.cnblogs.com/jasonnode/. On the learning site there are online exercises for each section you can try. Cookies

In a web app, it is necessary to share a "user session" between multiple requests. But the HTTP1.0 protocol is stateless. That's when the cookie comes up. How is that cookie handled?

Processing of cookies:

The server sends a cookie to the client's browser to save the cookie and then sends the cookie to the service every time the browser is requested. Before the HTML document is sent, the Web servers send a cookie by transmitting the Set-cookie message in the HTTP header Sent to the user's browser, as in the following example:

-nov-:: + GMT; 

Among the more important attributes:

    • Name=value: Key-value pairs, you can set the Key/value to be saved, note that the name here cannot be the same as the names of other property items
    • Expires: Expiration time (in seconds) after which the Cookie is invalidated at a certain point in time, such as Expires=wednesday, 09-nov-99 23:12:40 GMT
    • MaxAge: Maximum failure Time (MS), setting after how many failures
    • Secure: When the secure value is true, the cookie is invalid in HTTP and is valid in HTTPS
    • Path: Represents the path that the cookie affects, such as path=/. If the path does not match, the browser does not send this cookie
    • HttpOnly: It's Microsoft's expansion of cookies. If the "HttpOnly" attribute is set in the cookie, the cookie information will not be read by the program (JS script, applet, etc.) to prevent the XSS attack from producing
Cookies in node. js

How does node. JS want the client to send a cookie? There are two medium scenarios:

Using Response.writehead, the code is as follows:

//set the expiration time to one minutevarToday =NewDate ();varTime = Today.gettime () + -* +;varTime2 =NewDate (time);varTimeobj =time2.togmtstring (); Response.writehead ({'Set-cookie':'mycookie= "Type=ninja", "Language=javascript";p ath= "/";expires='+timeobj+'; httponly=true'});

Disadvantage: Use Response.writehead can only send once the head, that can only be called once, and can not coexist with response.render, or will error.

Using Response.cookie, the code example is as follows:

Response.cookie ('haha'name1=value1&name2=value2 ' , {maxAge:Ten*, path:'/', HttpOnly:true });

Syntax: Response.cookie (' cookiename ', ' name=value[name=value ...] ', [options]);

The meaning of the options for each field is explained above and is not repeated here.

Simple use of cookies

After the 4.x version, many modules, such as managing sessions and cookies, are no longer directly included in Express, ' but need to download and install the modules separately.

Cookieparser Installation:

$ NPM Install Cookie-parser

How to use:

varExpress = require ('Express');varCookieparser = require ('Cookie-parser'); varApp =Express (); App.use (Cookieparser ()); app.Get('/', Function (req, res) {//Check if the Isvisit field in the session exists//if present, add one more time, otherwise set the Isvisit field for the session and initialize it to 1.     if(req.cookie.isVisit) {req.cookie.isVisit++; Res.send ('<p> Section'+ Req.cookie.isVisit +'times to this page </p>'); } Else{req.cookie.isVisit=1; Res.send ("Welcome to the first time here."); Console.log ("Cookies:", req.cookies);//Print Cookies}}); App.listen ( the);

What is a session?

The session is another mechanism for recording the state of a customer, but the cookie is stored in the client browser and the session is stored on the server.

When the client browser accesses the server, the server logs the client information to the server in some form, which is the session. When the client browser accesses it again, it only needs to find the customer's status from that session.

If the cookie mechanism is to determine the customer's identity by checking the "pass" on the client, then the session mechanism verifies the customer's identity by checking the "customer schedule" on the server.

Session is equivalent to a program on the server set up a customer profile, when customers visit only need to query the customer file table on it.

The difference between the two:

    • The cookie data is stored on the client's browser and the session data is placed on the server.
    • Cookies are not very secure and others can analyze cookies stored locally and make cookie spoofing taking into account that security should use the session.
    • The session will be saved on the server for a certain amount of time. When the increase in access, will be compared to the performance of your server to reduce the performance of the server, you should use cookies.
    • A single cookie cannot hold more than 4K of data, and many browsers limit a maximum of 20 cookies per site.

Therefore, the suggestion: the login information and other important information stored as session, other information if necessary to retain, can be placed in a cookie

Simple application of Session

Like a cookie, you need a separate installation and Reference module, installation module: $sudo NPM Install Express-session The main method is the session (options), where options include optional parameters, mainly:

    • Name: In the Set cookie, save the field name of the session by default to Connect.sid.
    • Store:session storage, by default in memory, you can also use Redis,mongodb and so on. The express ecosystem has the support of corresponding modules.
    • Secret: By setting the secret string, the hash value is computed and placed in the 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.

Example:

varExpress = require ('Express');varSession = Resuire ('Session');varApp =exoress (); App.user ({secret:'Hubwiz App',//The value of secret suggests using a random stringCookie: {maxAge: -* +* -}//Expiration Time (milliseconds)}); app.Get('/', Function (req, res) {if(req.session.sign) {//Check if the user is already logged inConsole.log (req.session);//print the value of SessionRes.send ('welecome <strong>'+ Req.session.name +'</strong> Welcome to login again'); } Else{//otherwise show index pageReq.session.sign =true; Req.session.name='Hui Zhi Network'; Res.end ('Welcome to login! '); }}); App.listen ( the);

The session in node. JS, don't feel simple.

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.