Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 these variable could be used in another router page in nodejs.

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

like image 783
code_legend Avatar asked Nov 23 '16 03:11

code_legend


People also ask

Does NodeJS have sessions?

Most frameworks use their own session management middleware. For example, express , the most popular server framework for Node. js, has the accompanying express-session for session management.

How do I keep a session alive in node JS?

Try something like: app. use( session( { secret: 'keyboard cat', cookie: { maxAge: 60000 }, rolling: true, resave: true, saveUninitialized: false } ) );

How do I handle multiple sessions in node JS?

Here, since sess is global, the session won't work for multiple users as the server will create the same session for all the users. This can be solved by using what is called a session store. We have to store every session in the store so that each one will belong to only a single user.


1 Answers

Install express-session and use as follows:

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; 
});

Following code explain simple login and logout using session. The session we initialize uses secret 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('/');
    }
  });
});
like image 115
Satish Patel Avatar answered Sep 30 '22 11:09

Satish Patel