Use of cookies and sessions in Nodejs

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.