【问题标题】:Nodejs MySQL : TypeError: Cannot read properties of undefined (reading 'length')Nodejs MySQL:TypeError:无法读取未定义的属性(读取\'length\')
【发布时间】:2023-02-17 22:48:24
【问题描述】:

我已经使用 GitHub 在 Railway 上部署了我的 Node.js 项目。该应用程序已成功部署到远程 MySQL 数据库。部署后,应用程序工作正常并且成功查询了数据库,但是当应用程序闲置一段时间然后查询数据库时,应用程序崩溃了,因为从查询生成的 JS 对象的结果数组仍然未定义,我正在访问它的长度使用点运算符的属性。

code 到整个应用程序。

Martyrs-Welfare-Donation-System-MWDS/controllers/donor_auth.js 产生错误的地方——

db.query('SELECT * FROM donors WHERE email = ?', [email], async (error, results) => {
      console.log(results);
      if (results.length==0 || !(await bcrypt.compare(password, results[0].password))) {
        res.status(401).render('donor/donorlogin', {
          message: 'Email or Password is incorrect'
        })
      } else {
        const id = results[0].id;

        const token = jwt.sign({ id }, process.env.JWT_SECRET, {
          expiresIn: process.env.JWT_EXPIRES_IN
        });

        console.log("The token is: " + token);

        const cookieOptions = {
          expires: new Date(
            Date.now() + process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000
          ),
          httpOnly: true
        }

        res.cookie('jwt', token, cookieOptions);
        res.status(200).redirect('/donor/dashboard');
      }

    })

  } catch (error) {
    console.log(error);
  }
}

当我从铁路仪表板重新启动应用程序时,该应用程序再次正常工作。我尝试使用 async/await,但我认为它无济于事,并且未执行回调函数。

【问题讨论】:

    标签: javascript mysql node.js deployment railway


    【解决方案1】:

    当没有找到数据时,results变量为空,而不是空数组[]。将您的代码更改为如下所示:

    // Check null here
    if (!result || results.length==0 || !(await bcrypt.compare(password, results[0].password)))
    

    【讨论】:

      猜你喜欢
      • 2022-08-14
      • 1970-01-01
      • 2022-09-23
      • 2022-11-29
      • 2018-01-30
      • 1970-01-01
      • 2017-03-06
      • 2021-12-23
      • 1970-01-01
      相关资源
      最近更新 更多