【发布时间】:2021-11-25 03:33:43
【问题描述】:
我正在制作自己的小型 API,并且我已将以下 POST 请求编码到我的 MongoDB 数据库中:
api.post("/account/login", async (req, res) => {
const user = {
username: req.body.username,
password: req.body.password
};
const username = JSON.stringify(user.username);
const hashedPassword = await logincollection.find(user.username).toArray();
const hardCodedPassword = "$2b$10$q0iOBFTqqZ3vnp5oqDQUqejdS7UD/ayw4Q4qgi5hs1pfFI.xfipDS"
console.log(hashedPassword)
// Search for matching login credentials
logincollection.find(user, (err, result) => {
try {
if (bcrypt.compare(req.body.password, hardCodedPassword)) {
// Return credentials back to the client
const sendObject = {
username: result.username,
password: result.password
};
console.log(sendObject);
// Return code 200 (success) to the client
res.status(200).send(sendObject);
// Log to console when user logs in
console.log("User " + username + " logged in");
}
} catch(error) {
// If matching credentials were not found, return code 404 (wrong credentials) to the client
res.status(404).send()
}
})
})
我设置了一个有效的硬编码密码,用于纯粹的测试目的。处理此请求时,console.log(sendObject) 将未定义的结果打印到控制台,bcrypt 返回true,无论我输入什么密码。这里有什么问题?
【问题讨论】:
-
比较不返回布尔值。它返回一个 promise,这是真的。