简体   繁体   English

Node.js Express4-未定义的会话

[英]Nodejs express4 - undefined session

my problem is that my session is undefined as in new layers as even after "if" where the session value was set. 我的问题是,即使在设置会话值的“ if”之后,我的会话也未在新层中定义。

/*******************************************/
/**/  var express         = require('express'),
/**/      cookieParser    = require('cookie-parser'),
/**/      session         = require('express-session'),
/**/      bodyParser      = require('body-parser'),
/**/      ejs             = require('ejs'),
/**/      mysql           = require('mysql'),
/**/      md5             = require('md5');
/*******************************************/

var app = express();
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'samurai'
});

connection.connect(function(error) {
  if(error) {
    console.log("There is a problem with connection to the database.");
    return;
  }
    console.log("Connected with a database.");
});

app.use(cookieParser());
app.use(session({
    secret: 'test session',
    resave: false,
    saveUninitialized: true
}));

var sess;

Here my session is undefined (first I go to the '/sign' address): 这里我的会话是不确定的(首先我进入“ / sign”地址):

app.get('/', function(req, res) {
  sess = req.session;
  console.log("sesja = "+sess.login); <--------------- undefined

  if(sess.login) {
    res.render('indexo');
  } else {
    res.render('index');
  }
});


app.post('/sign', function(req, res, next) {
    sess=req.session;

    var query = 'SELECT * FROM ?? where ??=? AND ??=?';
    var table = ["users", "name", req.body.login, "password", md5(req.body.password)];
    query = mysql.format(query, table);
    connection.query(query, function(err, rows) {
      if(err) {
        console.log(err);
        return;
      } else if(rows.length > 0) {
        console.log("You have been sucessfully logged in.");
        sess.login = req.body.login;
        console.log(sess.login); <------------ works fine
      } else {
        console.log("The name or password is incorrect.");
      }
    });
    console.log(sess.login); <---------------- here again undefined
    res.end();
});

The problem is only in sessions case because if I create other global variable next to "var sess;" 问题仅在会话情况下,因为如果我在“ var sess”旁边创建其他全局变量; (for example var test;) and set for the variable a value in the "if" in '/sign" layer, then the "test" would be visible in the other layers and after that "if". (例如var test;),并在'/ sign'层的“ if”中为变量设置一个值,则“ test”将在其他层以及该“ if”之后可见。

The final question: Why the session.login is invisible after the "if" and in other layer? 最后一个问题:为什么session.login在“ if”之后和其他层中不可见? How to set it properly? 如何正确设置? Have you some tips for me with sessions creating? 您对创建会话有一些建议吗?

Thank you guys for your time and help. 谢谢你们的时间和帮助。

Setting global variables from an http request is an evil thing to do and is fraught with problems. 从http请求中设置全局变量是一件很邪恶的事,而且充满了问题。 First off, your server can have multiple requests in flight at the same time from different users. 首先,您的服务器可以同时处理来自不同用户的多个请求。 Using globals from requests like this means that different requests will "stomp" on each others globals and all sorts of chaos and bugs will ensue. 从这样的请求中使用全局变量意味着不同的请求将“踩住”彼此的全局变量,随之而来的是各种混乱和错误。

Stop using globals at all for session information. 完全停止使用全局变量获取会话信息。 If you need to communicate session info to other functions, then pass it to them as function arguments. 如果您需要将会话信息传递给其他函数,则将其作为函数参数传递给他们。

And, secondly you MUST understand how async operations work in node.js to have any chance of programming successfully in node.js. 其次,您必须了解node.js中的异步操作如何工作,以便有机会在node.js中成功编程。 You are making several mistakes with your asynchronous programming and that's one main reason why variables aren't set where you think they should be. 您在异步编程中犯了多个错误,这就是为什么未在您认为应该设置的位置设置变量的主要原因之一。

In this code: 在此代码中:

app.post('/sign', function(req, res, next) {
    sess=req.session;

    var query = 'SELECT * FROM ?? where ??=? AND ??=?';
    var table = ["users", "name", req.body.login, "password", md5(req.body.password)];
    query = mysql.format(query, table);
    connection.query(query, function(err, rows) {
      if(err) {
        console.log(err);
        return;
      } else if(rows.length > 0) {
        console.log("You have been sucessfully logged in.");
        sess.login = req.body.login;
        console.log(sess.login); <------------ works fine
      } else {
        console.log("The name or password is incorrect.");
      }
    });
    // this is executed BEFORE the connection.query() callback is called
    console.log(sess.login); <---------------- here again undefined
    res.end();
});

connection.query() is asynchronous. connection.query()是异步的。 T'hat means that it calls its callback sometime in the future. T'hat意味着它将在将来的某个时间调用其回调。 Thus your console.log(sess.login); 因此,您的console.log(sess.login); at the end of your request is happening BEFORE the callback has ever been called. 在您的请求结束之前,回调已经被调用过。

You aren't specific about exactly what you want to happen in all the cases in your query, but here's an outline for how the code could work: 您不确定在查询的所有情况下到底要发生什么,但是这里概述了代码的工作方式:

app.post('/sign', function(req, res, next) {
    var query = 'SELECT * FROM ?? where ??=? AND ??=?';
    var table = ["users", "name", req.body.login, "password", md5(req.body.password)];
    query = mysql.format(query, table);
    connection.query(query, function(err, rows) {
      if(err) {
        console.log(err);
        res.end("Query error");
      } else if(rows.length > 0) {
        res.end("Logged in successfully");
      } else {
        res.end("The name or password is incorrect.");
      }
    });
});

You may find this general answer on asynchronous responses useful: How do I return the response from an asynchronous call? 您可能会发现有关异步响应的一般性回答很有用: 如何从异步调用返回响应?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM