node.js - 当firestore查询中不存在数据时无限搜索循环
问题描述
我正在使用 Node.js(express) + firestore 实现登录控件。我尝试使用搜索查询来检查id
& 密码(pw
)。
如果用户输入数据(来自 HTML <form>
)在 firestore DB 中,客户端页面将重定向到/main
. else
将重定向回来。
当数据在firestore DB中时它可以工作,但是redirect
当数据不在firestore DB中时,它不适用于无限循环并且没有。
我检查了数据(id
,pw
)并进行了测试。但是当数据不在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');
});
解决方案
我自己通过使用找到了解决方案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('/');
});
推荐阅读
- python - 在 Gensim 中训练 word2vec 时如何控制随机性?
- python - 如何为熊猫中的每一行设置多个值
- mysql - ld:在 macOS Big Sur 11.4 上为 mysql2 gem Ruby 捆绑安装时找不到 -lzstd 的库
- bash - Linux shell - 以奇怪的格式解析日期
- java - 如何抑制具有 main 方法的类的 checkstyle HideUtilityClassConstructor 规则?
- javascript - 如何在 JS 的 cookie 中保存带有字典的列表?
- java - 在 JOOQ 的选择中使用 UNNEST
- flutter - Flutter:将字符串与点运算符一起使用
- java - 如何从动态标题/文本中仅提取数字?
- java - 如何从具有特定属性的 ArrayList 中打印一个或多个对象?