在节点中验证用户时获得奇怪的输出

时间:2023-01-25 21:54:23

I've created a function which grabs the users email & password and then runs a couple of checks in the database to see if the details are valid. If the details are valid then the user will get parsed back an API key.

我创建了一个抓取用户电子邮件和密码的函数,然后在数据库中运行几个检查以查看详细信息是否有效。如果细节有效,则用户将被解析回API密钥。

But for some reason, some functions are getting called before others and I'm getting undefined on a variable which is suppose to be returning the userObj.

但由于某种原因,某些函数在其他函数之前被调用,并且我对一个假设要返回userObj的变量进行了未定义。

In the function I've added console logs 0, 1, 2, 4, and 5 so you can see the weird outputs I'm getting when I call the function. I will include my code and console output below! I'm using sequalize for my models, I know they are returning the right data because I've tested it. I'm also using promises.

在函数中我添加了控制台日志0,1,2,4和5,这样你就可以看到我调用函数时得到的奇怪输出。我将在下面包含我的代码和控制台输出!我正在为我的模型使用sequalize,我知道他们正在返回正确的数据,因为我已经测试过了。我也在使用承诺。

Code:

var auth = {

  login: function(req, res) {

    var email = req.body.email || '';
    var password = req.body.password || '';

    // If nothing parsed, return json obj
    if (email == '' || password == '') {
      console.log("1");
      res.status(401);
      res.json({
        "status": 401,
        "message": "Invalid credentials"
      });
      return;
    }

    // Fire a query to your DB and check if the credentials are valid
    var dbUserObj = auth.validateUser(email, password);
    console.log("0 _____");
    console.log(dbUserObj); // I am returning undefined??? Why the!


    if (!dbUserObj) { // If authentication fails, we send a 401 back
      res.status(401);
      res.json({
        "status": 401,
        "message": "Invalid credentials"
      });
      return;
    }

    console.log("1 ____");
    authToken.create({ userId: dbUserObj.userId, token: genToken(dbUserObj)}).then(function(results){
      res.json("token", results.token);
    }); 
    console.log("2 ____");

  },
  validateUser: function(email, password) {
    // console.log(email + " pass: " + password);
    console.log("3 ____");

    user.findAll({
      where: {
        email : email,
        password : password
      },
      raw: true
    }).then(function(results) {
        console.log("4 _____");
        console.log(results);
        return results;
        // results prints out with all the correct values!!!!!!!!!!
    }).catch(function (err) {
      return err;
      console.log(err);
    });

    console.log("5 _____");
  },

Console output:

You can see that I'm getting undefined on the dbUserObj object, but I honestly don't know why because I'm printing out the results BEFORE I'm actually returning them (As you can see below).

您可以看到我在dbUserObj对象上未定义,但老实说我不知道​​为什么因为我在实际返回之前打印出结果(如下所示)。

3 ____
5 _____
0 _____
undefined
POST /login/ 401 1.341 ms - 46
Executing (default): SELECT `userId`, `name`, `password`, `email`, `authKey`, `profilePic`, `coverPic`, `description`, `createdAt`, `updatedAt` FROM `user` AS `user` WHERE `user`.`email` = 'jameswain10@gmail.com' AND `user`.`password` = 'f6588fc86e19db0936d9b7e8fd3d6c6544af6cdcc3ce161da88adcdb4b952adb';
4 _____ RESULTS ARE BELOW  ----
[ { userId: 1,
    name: 'James',
    password: 'f6588fc86e19db0936d9b7e8fd3d6c6544af6cdcc3ce161da88adcdb4b952adb',
    email: 'james@gmail.com',
    authKey: '$$$Ddjjdafjjadsfjadsjfjadfsj2',
    profilePic: 'default.png',
    coverPic: 'default.png',
    description: 'This user doesn\'t have a description!',
    createdAt: Wed Dec 23 2015 12:48:35 GMT+1100 (AEDT),
    updatedAt: Wed Dec 23 2015 12:48:35 GMT+1100 (AEDT) } ]

As you can see in the above console output, some logs are logging out before and after they should be? Does anyone know why this's happening!?

正如您在上面的控制台输出中所看到的,有些日志会在它们之前和之后注销?有谁知道为什么会发生这种情况!?

1 个解决方案

#1


2  

You're having issues with Async.

你遇到了Async的问题。

Have validate user return the promise:

有验证用户返回承诺:

validateUser: function(email, password) {
    // console.log(email + " pass: " + password);
    console.log("3 ____");

    return user.findAll({
      where: {
        email : email,
        password : password
      },
      raw: true
    });

In your login function, you can then then the results of that function.

在您的登录功能中,您可以随后获得该功能的结果。

login: function(req, res) {

    var email = req.body.email || '';
    var password = req.body.password || '';

    // If nothing parsed, return json obj
    if (email == '' || password == '') {
      console.log("1");
      res.status(401);
      res.json({
        "status": 401,
        "message": "Invalid credentials"
      });
      return;
    }

    // Fire a query to your DB and check if the credentials are valid
    auth.validateUser(email, password)
    .catch(function() { 
            //.. handle error
        }
    .then(function(results) {
        var dbUserObj = results;

        console.log("0 _____");
        console.log(dbUserObj); // I am returning undefined??? Why the!


        if (!dbUserObj) { // If authentication fails, we send a 401 back
        res.status(401);
        res.json({
            "status": 401,
            "message": "Invalid credentials"
        });
        return;
        }

        console.log("1 ____");
        authToken.create({ userId: dbUserObj.userId, token: genToken(dbUserObj)}).then(function(results){
        res.json("token", results.token);
        }); 
        console.log("2 ____");
      }
  },

BONUS ANSWER:

You were getting undefined because this line here:

你得到了未定义,因为这一行:

then(function(results) {
        console.log("4 _____");
        console.log(results);
        return results;
        // results prints out with all the correct values!!!!!!!!!!

This was returning the results to the "then" function which was creating another promise resolved with your dbobject, but then you didn't return it to the top function. Using promises in a function that doesn't return a promise or call a callback is a good red flag you're doing something wrong.

这会将结果返回到“then”函数,该函数创建了另一个使用dbobject解决的promise,但之后您没有将它返回到top函数。在不返回承诺的函数中使用promises或调用回调是一个很好的红旗,你做错了。

#1


2  

You're having issues with Async.

你遇到了Async的问题。

Have validate user return the promise:

有验证用户返回承诺:

validateUser: function(email, password) {
    // console.log(email + " pass: " + password);
    console.log("3 ____");

    return user.findAll({
      where: {
        email : email,
        password : password
      },
      raw: true
    });

In your login function, you can then then the results of that function.

在您的登录功能中,您可以随后获得该功能的结果。

login: function(req, res) {

    var email = req.body.email || '';
    var password = req.body.password || '';

    // If nothing parsed, return json obj
    if (email == '' || password == '') {
      console.log("1");
      res.status(401);
      res.json({
        "status": 401,
        "message": "Invalid credentials"
      });
      return;
    }

    // Fire a query to your DB and check if the credentials are valid
    auth.validateUser(email, password)
    .catch(function() { 
            //.. handle error
        }
    .then(function(results) {
        var dbUserObj = results;

        console.log("0 _____");
        console.log(dbUserObj); // I am returning undefined??? Why the!


        if (!dbUserObj) { // If authentication fails, we send a 401 back
        res.status(401);
        res.json({
            "status": 401,
            "message": "Invalid credentials"
        });
        return;
        }

        console.log("1 ____");
        authToken.create({ userId: dbUserObj.userId, token: genToken(dbUserObj)}).then(function(results){
        res.json("token", results.token);
        }); 
        console.log("2 ____");
      }
  },

BONUS ANSWER:

You were getting undefined because this line here:

你得到了未定义,因为这一行:

then(function(results) {
        console.log("4 _____");
        console.log(results);
        return results;
        // results prints out with all the correct values!!!!!!!!!!

This was returning the results to the "then" function which was creating another promise resolved with your dbobject, but then you didn't return it to the top function. Using promises in a function that doesn't return a promise or call a callback is a good red flag you're doing something wrong.

这会将结果返回到“then”函数,该函数创建了另一个使用dbobject解决的promise,但之后您没有将它返回到top函数。在不返回承诺的函数中使用promises或调用回调是一个很好的红旗,你做错了。