About session and cookies I've been doing this for 2-3 days, and I find this thing a lot of trouble. Many tutorials keep this conversation in NoSQL, such as MONGO, or Redis, and so on. But I still want to keep it in my computer's memory, which is more traditional. There are many articles on the Internet, but basically you copy me, I copy you, And Express has a lot of this session/cookie middleware, always confusing. Many articles are donuts, completely rely on their own slowly to try, to read the document, to explore.
I am based on the middleware of Connect. This middleware feature is very powerful
Interested students can refer to: http://blog.fens.me/nodejs-connect/
Installation here will not say. Here we come to realize, we hope to be useful to everyone
Import module in App.js
1 var connect = require (' Connect ');
Join before routing the distribution statement.
1 App.use (Bodyparser.json ()), 2 App.use (bodyparser.urlencoded ()), 3 App.use (Cookieparser ()), 4 App.use ( Connect.session ({secret: ' lgphp ', key: ' lgphp ', cookie: {maxage:20000}})); Session duration is 20 seconds, this is in milliseconds, so we set up a session sessions, which is a global setting of 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 ', ' I am a cookie ', {maxage: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 '); }
Original: Http://www.cnblogs.com/lgphp/p/3913077.html?utm_source=tuicool&utm_medium=referral
EXPRESS 4.x above use of session and Cookie Records