【问题标题】:Nodejs and postgres: returning data from query for password validationNodejs和postgres:从查询中返回数据以进行密码验证
【发布时间】:2022-01-11 23:59:33
【问题描述】:

我是 javascript/nodejs 的新手,我正在尝试构建一个简单的登录,其中我有一个应该返回查询结果的函数。

我如何配置连接;

pg.defaults.ssl = true;
let dbClient = new pg.Client(conString);
dbClient.connect();

回调函数;

    app.post("/login", urlencodedParser, function(req, res) {

  let uName = req.body.username;
  let pwdInput = req.body.password;
  let fetchedPwd;

  function fetchPwd (usr, callback) {

     dbClient.query("SELECT pwd FROM users where username = $1", [usr], function (err, res) {

       if (err) {
         callback(err, null);
        }

        else {
          callback (null, res[0].pwd);
        }
     });}

函数调用;

fetchPwd(uName, function(err, res) {
if (err) {
  console.log(err);
}
else {
  fetchedPwd = res;
}})

支票;

  if (pwdInput == fetchedPwd) {
    req.session.user = uName;
    res.redirect("/");
  }

  else {

    res.render("login", {login_error: "Wrong user and password combination!"});
  }

});

我所期望的; 回调函数返回一个字符串,然后我可以检查输入。

遇到的错误; 错误:客户端已关闭且不可查询

出于测试目的,我在文件末尾注释掉了dbClient.end(); 之后callback (null, res[0].pwd); 行抛出以下错误; TypeError: Cannot read properties of undefined (reading 'pwd')

(pwd 是数据库中正确的列名)

我不明白为什么会出现这些错误。 按照我的预期,函数应该在到达dbClient.end(); 之前完成。

同样适用于第二个错误; res[0].pwd 怎么可能是未定义的,当查询结果显然不是空的,因为到达了 else 语句?

【问题讨论】:

    标签: node.js postgresql express callback pg


    【解决方案1】:

    我找到了关于为什么遇到上述错误的答案;

    1. 围绕数据库连接的奇怪行为是因为 pg 的配置已过时。 我现在将配置更改为:

      const dbConfig = {
             connectionString: conString,
             ssl: { rejectUnauthorized: false }
           }
           var dbClient = new pg.Client(dbConfig);
           dbClient.connect();
      

    我也不再关闭连接,只是保持连接。

    1. 虽然我仍然不确定为什么我的旧函数不起作用,但我已经重写了我的函数,现在一切都按预期工作了;

      app.post("/login", urlencodedParser, function(req, res) {
      
      let uName = req.body.username;
      let pwdInput = req.body.password;
      
      let User = {
       username: uName,
       password: ""
      }
      
      function fetchPwd (usr) {
       dbClient.query("SELECT pwd from users where username = $1", [usr], function (dbError, dbResponse) {
      
         User.password = dbResponse.rows[0].pwd;
      
         if (pwdInput == User.password) {
           req.session.user = uName;
           res.redirect("/");
         }
      
         else {
           res.status(400).render("login", {login_error: "Wrong user and password combination!"});
           console.log("wrong login");
         }
       });
      }
      
      fetchPwd(User.username);
      
      });
      

    【讨论】:

      猜你喜欢
      • 2020-10-08
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-23
      • 2021-12-14
      相关资源
      最近更新 更多