The nature of the session is achieved using cookies.
The principle is roughly: http brings the server to set cookies in advance, the server gets the cookies marked with the user's identity, and then goes to a fixed location (database, file) to retrieve the corresponding user's identity. Assign the identity to the request for this request, and the user's identity will be known during the program processing. (It will be automatically implemented in PHP, ASP or other server languages)
Implement cookies
A cookie that can indicate the user's identity needs to be set for each user. The following rules can be used
Register the mailbox MD5 value + password MD5 value + random code MD5 value. (For example just, this may not be a good solution)
Server code snippet:
The code copy is as follows: res.setHeader("Set-Cookie", ["sid="+newUser.toCookie()+";path=/;domain="+config.domain+";expires="+new Date("2030") ]);
Cookies
The code copy is as follows:sid=275fccab7935736ff68c95c3ddbfaaee|275fccab7935736ff68c95c3ddbfaaee|275fccab7935736ff68c95c3ddbfaaee
Use cookies to get user identity and set session
Direct all non-static resource requests here for processing. Get the cookie, split the cookie and look for users who meet the criteria in the database. Finally, use next to jump to the next request logic.
The next request logic can directly use req.session.user to obtain the user object.
The code copy is as follows: session:function(req, res, next){
req.session = {};
if( req.cookies && req.cookies.sid ){
var a = req.cookies.sid.split("|");
var hexMail = a[0];
var hexPwd = a[1];
var hexRandom = a[2];
UserModel.hexFind(hexMail, hexPwd, hexRandom, function( status ){
//console.log("hexFind", status );
if(status.code == "0"){
//req.cookiesSelecter = cookiesSelecter;
req.session.user = status.result;
}
next();
});
}else{
next();
}
}
The above is all the simple use of nodejs session. I hope it can give you a reference and I hope you can support Wulin.com more.