简体   繁体   中英

query in knex js for users and password validation

I want to create a query with knex js using the data from the template (using handlebars and expressjs) to validate a user. I created a query and then added it to a variable that after validate the user to login. The point is that I am having troubles to make the knex query to do what I want it to do, and I don't know what I am doing wrong.

    var usernameReq = req.body.username;
    var passwordReq = req.body.password;
    var pass;
    knex('users').where({
    username: usernameReq }).select('password').then(
    function(result){
        pass = result;
        }).catch(function(error) {
    console.log(error);
});

if (passwordReq === pass){
  //login  
}

Knex uses promises, that are asynchronous.

the if (passwordReq === pass) is outside the promise. That means the result will not be available.

Place the if and all code depending on the query result (such as the http response itself) inside the then(...) .

Note also the result is an array of objects, even when referencing a single column of a single line. So to refer to the password you must use result[0].password

var usernameReq = req.body.username;
var passwordReq = req.body.password;
knex('users')
  .where({ username: usernameReq })
  .select('password')
  .then(function(result) {
    if (!result || !result[0])  {  // not found!
      // report invalid username
      return;
    }
    var pass = result[0].password;
    if (passwordReq === pass) {
      // login
    } else {
      // failed login
    }
  })
  .catch(function(error) {
    console.log(error);
  });

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