How to use session variable with NodeJs?

I have the following NodeJS code:

let sql = `SELECT box_id, cubby_id, occupied, comport FROM box WHERE longestDimension = ? AND LOWER(box_id) = LOWER(?)`; connection.query(sql, [boxSelectedDimension, boxSelectedValue] , function(err, rows, fields) { if (!err) { for(var i=0; i< rows.length; i++) { // Make the comparaison case insensitive if (rows[i].occupied == `unoccupied`) { console.log("free"); var comport = rows[i].comport; var command = "open" + rows[i].cubby_id; 

Essentially, I would like to store the value of the comport and command variable in a session variable so that the value of this variable can be used on another page of the router in nodejs.

I am not sure how to store and retrieve the session variable.

+15
source share
1 answer

Install express-session and use the following:

 var express = require('express'); var session = require('express-session'); var app = express(); app.use(session({secret:'XASDASDA'})); var ssn ; app.get('/',function(req,res){ ssn=req.session; /* * Here we have assign the 'session' to 'ssn'. * Now we can create any number of session variable we want. * Here we do like this. */ // YOUR CODE HERE TO GET COMPORT AND COMMAND ssn.comport; ssn.command; }); 

The following code explains a simple login and logout using a session. In the session we initialize, secret used to store cookies . Hope this helps.

 var ssn; app.get('/',function(req,res) { ssn = req.session; if(ssn.email) { res.redirect('/admin'); } else { res.render('index.html'); } }); app.post('/login',function(req,res){ ssn = req.session; ssn.email=req.body.email; res.end('done'); }); app.get('/admin',function(req,res){ ssn = req.session; if(ssn.email) { res.write('<h1>Hello '+ssn.email+'</h1>'); res.end('<a href="+">Logout</a>'); } else { res.write('<h1>login first.</h1>'); res.end('<a href="+">Login</a>'); } }); app.get('/logout',function(req,res){ req.session.destroy(function(err) { if(err) { console.log(err); } else { res.redirect('/'); } }); });` 
+22
source

Source: https://habr.com/ru/post/1260184/


All Articles