Node Js Session management demo

General Tech Bugs & Fixes 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

Can anybody tell me how to make session variable in Node Js and how to browse that. Actually I am working on Node Js and with Express

    exports.setSession=function(req,res){
req.session.user = 'demo';
//console.log("adding to session " + JSON.stringify(user));
console.log("SessionS-"+req.session.user);
    };


   exports.get_session = function(req, res){
console.log("SessionFun-"+req.session.user);
 };

I did this way but getting undefined value in session var

 Output:         
     SessionS-demo
     SessionFun-undefined
profilepic.png
manpreet 2 years ago

 

Express is based on a connect middleware, so you can reuse connect session implementation rather than writing you own. Example code you can find below.

var http = require('http')
  , express = require('express')
  , app = express();

app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));

app.get('/set',function(req, res){
    req.session.user = { name:'andbas' };
    res.send('Session set');
});

app.get('/get',function(req, res){
    res.send(req.session.user);
});

http.createServer(app).listen(3000, function(){
    console.log('Express server listening on port 3000');
});

This code set the session user variable when you make a GET /set call, and post it back to you when you do the GET /get. Just try it.

Mistake you do in your own code is that you only modify the req variable, which node http module create for each request. It's not the place where you could hold the data. Instead of this you need to user HTTP headers to setup the key, which will be used to recognize the user and store it data on server (I greatly simplified the concept to make it more understandable). You can review the code in the connect session to understand how it works.


0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.