如何在 NodeJs 中使用会话变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40755622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:50:02  来源:igfitidea点击:

How to use session variable with NodeJs?

node.jssessionexpress

提问by John

I have the following NodeJS code:

我有以下 NodeJS 代码:

  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 comportand commandvariable in a session variable so that the value of these variable could be used in another router page in nodejs.

本质上,我想将comportcommand变量的值存储在会话变量中,以便这些变量的值可以在 nodejs 的另一个路由器页面中使用。

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

我不确定如何存储和检索会话变量。

回答by Satish Patel

Install express-sessionand use as follows:

安装express-session和使用如下:

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 sessionwe initialize uses secretto store cookies. Hope this helps.

以下代码解释了使用会话的简单登录和注销。在session我们初始化使用secret存储cookies。希望这可以帮助。

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('/');
    }
  });
});`