Node cookie and Session usage

Source: Internet
Author: User
Tags sesion

Import module in App.js

Require (' connect ');

Join before routing the distribution statement.

1app.use (Bodyparser.json ()); 2 app.use (bodyparser.urlencoded ()); Span style= "color: #008080;" >3 app.use (Cookieparser ()); 4 app.use (connect.session ({secret:  ' lgphp ', cookie: {maxAge: 20000}}); //session The duration is 20 seconds, this is in milliseconds, so we set up a session, which is a global setting < Span class= "number" >5 routes (app);             

First say session, set the session KV

Req.session.sessname = ' I am a sesion ';

So we set up a session variable named Sessname, the value is Iam a sesion, the session duration is 20 seconds. Typing on Ubuntu is still not very flexible

Get session

Res.Send (' session: ' + req.session.sessname) 

Delete session

Req.session.destroy ();

Determine if the session exists

if (req.session) {   // Determine if session is destroyed 

The above session operation is enough to complete the usual logic.

The following is a cookie, which we often use.

Set cookies

1   res.cookie (' cookiename ',20000,httponly:True, Path:'/'});  cooike      Duration (sec)

Get the value of a cookie

var c = req.cookies.cookiename   // This is a Dictionary object, you can use parentheses to get 

Delete cookies, many online, but it seems to be useless, some have set the expiration time to 0, I tried, the value of the cookie is not, but the cookie is still in, with Chrome to see there.

Res.cookie (' cookiename ', ' null ', {maxage:0});

There's no problem with deleting it.

Determine if a cookie exists, such as login and permission verification. After the cookie expires, it becomes a undefined, so we judge

if (' undefined ' = = = = (typeof Req.cookies.cookiename)) {res.send (' deleted cookie ');}   

Node cookie and Session usage

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.