Session management in Nodejs

后端 未结 3 1710
南方客
南方客 2021-01-13 10:58

I am beginner of NodeJS.And just started a simple project where I need a session management concept. So How to manage the session in NodeJS application.

In my projec

3条回答
  •  长情又很酷
    2021-01-13 11:22

    For the session management we need a middleware 'cookie-parser'.Previously it is the part of express but after express 4.0 and later it is a separate module.

    So to access the cookie parser we need to install in our project as :

    npm install cookie-parser --save

    Then add this into your app.js file as :

    var cookieParser = require('cookie-parser');
    
     app.use(cookieParser()); 

    Then we reqired session module. So first of all install the session module by :

    npm install express-session --save

    Then to enable the session. we add below code in app.js file.

    app.use(session({secret:config.sessionSecret, saveUninitialized : true, resave : true}));

    Then come to the routes.js file :-

    Let us suppose there is a session variable favColor. Now using session set the color and get in the other page. the code is look like :-

    router.get('/setColor', function(req , res , next){
            req.session.favColor = 'Red';
            res.send('Setting favourite color ...!');
        });
        
        router.get('/getColor', function(req , res , next){
            res.send('Favourite Color : ' + (req.session.favColor == undefined?"NOT FOUND":req.session.favColor));
        });

    This is all about the session management.We can also learn more about the session :- This Reference

提交回复
热议问题