如何添加catch语句以修复未处理的承诺拒绝警告

时间:2019-04-03 18:53:57

标签: javascript node.js promise bcrypt

我正在尝试将用户身份验证添加到我的站点。页面上的注册路由运行正常,但是当我尝试向登录路由发送请求时,收到未处理的承诺拒绝警告。

我尝试添加.catch(err => console.log(err));.catch(console.log("Something's gone wrong."));.findOne().then().compare().then()的结尾,但这没有帮助。

router.post("/login", (req, res) => {
  const email = req.body.email;
  const password = req.body.passowrd;

  User.findOne({ email }).then(user => {
    if (!user) {
      return res.status(404).json({ email: "User not found" });
    }

    bcrypt.compare(password, user.passowrd).then(isMatch => {
      if (isMatch) {
        res.json({ msg: "Success" });
      } else {
        return res.status(400).json({ password: "Password incorrect" });
      }
    });
  });
});

该代码应该简单地发送回一条密码匹配的消息,以便以后可以生成令牌。我收到此错误:

(node:18152) UnhandledPromiseRejectionWarning: Error: Illegal arguments: undefined, undefined
    at _async (/home/jok/code/node_modules/bcryptjs/dist/bcrypt.js:286:46)
    at /home/jok/code/node_modules/bcryptjs/dist/bcrypt.js:307:17
    at new Promise (<anonymous>)
    at Object.bcrypt.compare (/home/jok/code/node_modules/bcryptjs/dist/bcrypt.js:306:20)
    at User.findOne.then.user (/home/jok/code/routes/api/users.js:64:12)
    at processTicksAndRejections (internal/process/next_tick.js:81:5)
(node:18152) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:18152) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

2 个答案:

答案 0 :(得分:0)

UnhandledPromiseRejectionWarning的发生是因为您没有处理Promise拒绝,这意味着您缺少.catch处理程序。

bcrypt.compare(password, user.passowrd).then(isMatch => {
  if (isMatch) {
    res.json({ msg: "Success" });
  } else {
    return res.status(400).json({ password: "Password incorrect" });
  }
})
.catch(err => {
    res.status(500).send('Internal server error');
});

在这种情况下,似乎passworduser.passowrdundefined。后者可能是由于输入错误:passowrd => password

因此,建议检查发送到您的路由的参数是否有效。

router.post("/login", (req, res) => {
  const email = req.body.email;
  const password = req.body.passowrd;

  if(!email || !password)
    return res.status(400).send('email & password are required');

  /* ... */
});

由于您同时在.catch .findOne上也缺少Promise处理程序,因此最好将链Promises链接起来,而不要像嵌套操作那样嵌套它们。所以这是完整的代码:

router.post("/login", (req, res) => {
    const email = req.body.email;
    const password = req.body.passowrd;

    if (!email || !password)
        return res.status(400).send('email & password are required');

    User.findOne({ email })
        .then(user => {
            if (!user) {
                return res.status(404)
                    .json({ message: "User not found" });
            }

            return bcrypt.compare(password, user.passowrd);
        })
        .then(isMatch => {

            if (typeof isMatch !== 'boolean')
                return; // result from `res.status(404)...`

            if (isMatch)
                return res.json({ message: "Success" });

            return res.status(400)
                .json({ message: "Password incorrect" });

        })
        .catch(err => {
            res.status(500).json({ message: 'Internal server error' });
        });

 });
  

我尝试添加.catch(err => console.log(err));和   .catch(console.log(“出问题了。”));到两者的结尾   .findOne()。then()和.compare()。then(),但这没有帮助。

您未正确附加处理程序,或者警告已在另一个代码中触发。但是由于提供的代码中没有您提到的.catch,因此无法确认。无论如何,以上代码段都不会触发UnhandledPromiseRejectionWarning

答案 1 :(得分:0)

bcrypt.compare(myPlaintextPassword, hash, function(err, res) {
    if (err) {
      console.log(err);
    }
    
    // Use your response
});

在简单的逻辑中使用诺言是不必要的。