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