How to use session variable with NodeJs?

后端 未结 1 1451
误落风尘
误落风尘 2020-12-30 05:02

I have the following NodeJS code:

  let sql = `SELECT box_id, cubby_id, occupied, comport
           FROM box
           WHERE longestDimension = ?
                  


        
相关标签:
1条回答
  • 2020-12-30 05:37

    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('/');
        }
      });
    });`
    
    0 讨论(0)
提交回复
热议问题