Today, the elephant brother used the connect session and cookie, and it feels quite helpful. Share it with me (there are a lot of pitfalls in it, the document is too vague, and it took a lot of time ). Connect is a node middleware (middleware) framework. Specific not table, see the official website to introduce http://www.senchalabs.org/connect/
Under app. js configuration (must be placed in app. use (routes)
The Code is as follows:
Var connect = require ("connect ");
App. use (connect. cookieParser ());
App. use (connect. session ({secret: 'jiami ', cookie: {maxAge: 60*60*24*1000 }}));
Then use
The Code is as follows:
// Set
Req. session. username = "sess_username ";
Req. session. password = "sess_admin ";
Req. session. your = {username: "sess_name", password: "sess_pwd "};
// Use
Console. log (req. session. username );
Console. log (req. session. your );
Other methods
The Code is as follows:
// Cancel the session
Req. session. destroy (function (err ){
Console. log (err );
})
// Regenerate the sid
Req. session. regenerate (function (err ){
Console. log (err );
});
After the session is set, we can see that there is a sid in the cookie to record the session ID.
Print req. cookies and req. session objects
The Code is as follows:
Console. log (req. cookies );
Console. log (req. session );
We can see that the session is connected to the client by saving a connect. sid, but the session is stored in the memory.
2, cookie, the official documentation :( http://www.senchalabs.org/connect/cookieParser.html this document pitted me for a whole day), not to mention the table, the following example is a brother to try out, because the document did not write the use method
Set
The Code is as follows:
// Set cookie
Res. cookie ("user", {username: "cookie_name", password: "cookie_pwd"}, {maxAge: 60*60*24*1000, httpOnly: true, path: '/'});
Res. cookie ("msg", "username or password cannot be blank", {maxAge: 60*60*24*1000 });
Delete
The Code is as follows:
Res. cookie ("msg", "username or password cannot be blank", {maxAge: 0 });