javascript - 使用 express 查找单个 mongo 文档
问题描述
我是 MongoDB 的新手,特快。我想用他的用户名和密码验证用户。但即使我使用正确的凭据,我的代码也没有给出任何错误并执行“else 语句”。
这是JS文件:
app.post('/auth', function(req, res){
var user = ( db.collection('auth').findOne({name: req.body.username}));
var pass = ( db.collection('auth').findOne({password: req.body.password}));
if(user == req.body.username && pass == req.body.password){
res.send("Credentials Match");
}else{
res.send("Wrong Credentials");
}
console.log(req.body);
})
这是 HTML 文件:
<form class="form-signin" action="/auth" method="POST">
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="inputEmail" class="sr-only">Username</label>
<input type="text" placeholder="Username" name="username" required="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" placeholder="password" required="">
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
解决方案
这两行
var user = ( db.collection('auth').findOne({name: req.body.username}));
var pass = ( db.collection('auth').findOne({password: req.body.password}));
代表异步代码,因此if else
检查不会等待它们被执行
除非您下令javascript
等待
您可以使用async/await
强制代码等到异步部分完成
另外,您仅获取用户名,然后也仅获取密码
所以如果用户输入他的名字,但另一个密码而不是他的正确密码,并且这个密码存在于数据库中,登录将完成,而它不应该
您必须检查同一文档中的用户名和密码以避免这种情况
类似的东西
app.post('/auth', async function(req, res) { // note the async keyword here
try {
var user = await db.collection('auth').findOne({ name: req.body.username , password: req.body.password });
if (user && user.name == req.body.username && user.password == req.body.password) {
res.send("Credentials Match");
} else {
res.send("Wrong Credentials");
}
console.log(req.body);
}
catch (err) {
console.log('Exception >>\n', err); // log the error
res.send("Something wrong has happened while checking the credentials");
}
})
希望能帮助到你
推荐阅读
- r - R ggplot2 循环,用于为不同的行子集创建单独的输出
- javascript - 在 Discord Chat (DISCORD.JS) 中让 Discord Bot 显示“Bot is typing...”
- sql - 在 Microsoft Access VBA 中使用替换编辑直通 SQL 查询
- symfony-4.4 - Symfony security.yml access_controls 带有可选前缀的多语言
- php - Php 按流明中的标题排序
- mysql - 与VPN连接的MySQL数据库中的复制问题
- android - Google 表格从表格 android 应用程序或 script.google.com 发布到网络
- css - 搜索栏在小屏幕引导 css 上消失
- python - 我有一个配对列表,我想根据第二个配对过滤这个列表
- azure-functions - MassTransit RespondAsync() 引发 Microsoft.Azure.ServiceBus.MessagingEntityNotFoundException