【问题标题】:Infinite search loop when the data is not exists in firestore query当firestore查询中不存在数据时无限搜索循环
【发布时间】:2019-05-19 13:28:47
【问题描述】:

我正在使用 Node.js(express) + firestore 实现登录控件。 我尝试使用搜索查询进行id 和密码(pw)检查。

如果用户输入数据(来自 HTML <form>)在 firestore DB 中,客户端页面将重定向到 /mainelse 将重定向回来。

当数据在 firestore 数据库中时它可以工作,但是当数据不在 firestore 数据库中时,它不适用于无限循环并且没有redirect

我检查了数据(idpw)并进行了测试。但是当数据不在firestore DB中时,它总是无限循环。

查看代码是这样的。

    <form action="" method="post">
      <input placeholder="ID" name="id" id="id" type="text">
      <input placeholder="PASSWORD" name="pw" id="password" type="password">
      <button type="submit">SIGN-IN</button>
    </form>
    <button onclick="location.href='/signup'">SIGN-UP</button>

而服务器中的代码是这样的

var users_info = db.collection('users')
    .where('id', '==', req.body.id).where('pw', '==', sha256(req.body.pw))
    .get().then(snapshot => {
      snapshot.forEach(doc => {
        if (doc.exists) {
          req.session.user = {
            'id': doc.data().id,
            'name': doc.data().name,
            'auth': doc.data().auth,
            'is_guest': doc.data().is_guest
          }
          res.redirect('/main');
        } else {
          res.redirect('back');
        }
      });
    })
    .catch(err => {
      console.log(err);
      res.redirect('back');
    });

【问题讨论】:

标签: node.js google-cloud-firestore


【解决方案1】:

我自己通过snapshot.empty找到了解决方案。

var users_info = db.collection('users')
    .where('id', '==', req.body.id).where('pw', '==', sha256(req.body.pw))
    .get().then(snapshot => {
      if(snapshot.empty) {
        res.redirect('/');
      }
      else{
        snapshot.forEach(doc => {
          if (doc.exists) {
            req.session.user = {
              'id': doc.data().id,
              'name': doc.data().name,
              'auth': doc.data().auth,
              'is_guest': doc.data().is_guest
            }
            res.redirect('/main');
          } else {
            res.redirect('/');
          }
        });
      }

    })
    .catch(err => {
      console.log(err);
      res.redirect('/');
    });

【讨论】:

    猜你喜欢
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多