首页 > 解决方案 > Express JS 查询错误处理不起作用

问题描述

这是我在 Stackoverflow 上的第一篇文章,请善待。

我有一个大问题,我无法通过谷歌搜索来解决(这非常罕见)。我想在我的查询中创建一个简单的错误处理,但它不起作用。

这是代码:

pool.query("SELECT password_hash FROM User WHERE email = ?",
    req.body.EMailLogin, (error, results, fields) => {
      
      if(error) {
        // It executes the if aswell as the else statement and I dont know why (if(error) seems to be ignored even if its true)
      } else {
        // And then it crashes here, because password_hash is undefined
        let hash = results[0].password_hash;
        bcrypt.compare(req.body.PasswordLogin, hash, function(err, result) {
          if (result == true) {
            ses.user = req.body.EMailLogin;
            req.session.cookie.expires = false;
            req.session.save(() => {
              return res.redirect('/index');
            });
          } else {
            res.render(); // My Page for Wrong Password (ignore this)
          }
        });
      }
    }
  );

标签: mysqlnode.jsexpress

解决方案


Throwif里面的错误

if(error) {
        throw error;
      } else {

我认为错误是您传递参数的方式,它应该是一个数组:

pool.query("SELECT password_hash FROM User WHERE email = ?",
    [req.body.EMailLogin],

我希望这可以解决您的问题。


推荐阅读