简体   繁体   中英

Writing a login in node.js using express

I'm writing a login for a website in node.js using the express framework. However, the code is executing in a weird order and I'm not sure how to fix it. Here's a simplified version of the relevant code:

app.post('/login', function(req, res){
    var login_error;
    if (!req.session.username) { //if no one is logged in
        if (req.body.user != undefined && req.body.pass != undefined) {
            client.query('USE data', function(error, results) {}
        });
        client.query('SELECT id FROM user WHERE username=? AND password=?',[reg.body.user, req.body.pass],
        function(err, results,fields) {
            if (err || results.length == 0) {
                login_error=1;
                console.log('a '+login_error); //LINE A
            }
        });
    }
    console.log('b '+login_error);  //LINE B
    if (login_error == undefined) {
        req.session.username=req.body.user;
    }
    client.end();
}
res.render('login', {
    user: req.session.username,
    login_error: login_error
});

The page is always rendering with login_error=undefined, even when the username/pass combo is not in the database. In this case LINE A is printing login_error=1, but LINE B is printing login_error=undefined. Furthermore LINE B prints before LINE A even though it appears later. I'm not really sure what's going on here.

This is happening because of the way callbacks work. In this code:

    client.query('SELECT id FROM user WHERE username=? AND password=?',[reg.body.user, req.body.pass],
    function(err, results,fields) {
        if (err || results.length == 0) {
            login_error=1;
            console.log('a '+login_error); //LINE A
        }
    });

the function containing line A is not executed immediately. Instead, client.query returns immediately and execution continues, towards line B.

Then when the select query returns, your callback function executes. So, in order of execution, it will probably come after line B, even though it appears in the source beforehand.

Consider this example

client.query('SELECT 1 AS Res', function(err, results) {
  console.log(results.fields.Res);
});

client.query('SELECT 2 AS Res', function(err, results) {
  console.log(results.fields.Res);
});

you might well find this producing the following output:

2
1

Because the second query might return faster than the first.

This is the source of Node's power - the code doesn't block, it's asynchronous, so it's fast .

To get your example working as intended, you should refactor it to call the code that needs to aware of the results of the query in a separate function. For example something more like this:

function processLogin(login_error) {
  console.log('b '+login_error);  //LINE B
  if (login_error !== true) {
    req.session.username=req.body.user;
  }

  res.render('login', {
      user: req.session.username,
      login_error: login_error
  });
}

app.post('/login', function(req, res){
    if (!req.session.username) { //if no one is logged in
        if (req.body.user != undefined && req.body.pass != undefined) {
            client.query('USE data', function(error, results) {}
        });
        client.query('SELECT id FROM user WHERE username=? AND password=?',[reg.body.user, req.body.pass], function(err, results,fields) {
            if (err || results.length == 0) {
                process_login(true);
            } else {
                process_login(false);
            }
        });
    }
    client.end();
}

This code won't work straight away, but notice how I've moved the res.render call into a function, which I'm calling from the callback of client.query. Now, you'll need to allow that callback to access the res variable, either by making it global (which is fine if you're inside a dedicated 'login' module, but otherwise a bad idea), or by passing it to the function as an argument, which might be preferable.

Just because a line of code appears after another, doesn't necessarily mean it will be executed after it, if there's a callback involved. Something which acts similarly which you might be familiar with is timeouts; consider this:

setTimeout(function() {
  console.log(1);
}, 1000);
console.log(2);

In this case, it should be obvious that you'll see the following:

2
1

It's exactly the same with callbacks to things like mysql queries. Instead of the entire process waiting for client.query to return, execution continues and you put everything that relies on the results from client.query into a callback which you send to client.query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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