Because of the stateless nature of the HTTP session, a cookie appears in order to mark the user's logon status. There are many types of cookies, such as ordinary cookies, signature cookies, JSON cookies, etc., which are mainly recorded in the Express application where the use of cookies and session is configured.
Cookies
The first is the configuration in App.js:
... var cookieparser = require (' Cookie-parser '); var bodyparser = require (' Body-parser '); App.use (Cookieparser (' This was the secret key for singed (Cookies ')) .....
The use of JS routing is relatively simple:
Router.post ("/setcookie",function(req,res, next) { var addr = req.body.a; Set a cookie, configure the Signed:true to configure the signature cookie
Res.cookie (true//, signed:true Next ();});
Get cookies
var a = req.cookies.addr;
var a = req.signedcookies[' addr ']; Get Signature Cookieconsole.log (a);
Session
App.js configuration:
...varSession = Require ("Express-session");varCookieparser = require (' Cookie-parser '));.. app.use (Session ({secret:' This was the secret for Cookie ', Resave:false, saveuninitialized:true}); App.use (function(req, res, next) {varURL =Req.originalurl; if(URL! = "/" && undefined = =req.session.user) {if(URL! = "/create/article") {//Troubleshooting session interception for/create/article routingRes.send (' <script>top.location.href= '/';</script> '); return; }} (Next ();});
In the route directly through the following settings or get session data:
var user = req.session.user;console.dir (user);
Purge of Session:
Req.session.destroy (function(err) { res.redirect ('/');})
Use of cookies and sessions in Nodejs