api - Hashing passwords using bcrypt without a database
问题描述
I created an endpoint to register new users, /register
.
Since I'm not using a database, I'm updating an array by pushing the new user into it, and then writing this new array into a json
file using fs.writeJSONFile()
.
Below is the code for registering a new user:
router.post("/register", m.checkFieldsPost, async (req, res) => {
const { email, password } = req.body;
const id = { id: helper.getNewId(users) };
try {
const user = await helper.findUser(users, email);
console.log(`user is ${user}`);
if (user)
return res.status(400).json({
message: "That user already exists!",
});
// Generate salt
const salt = await bcrypt.genSalt(10);
// Hash password
const hashedPassword = await bcrypt.hash(password, salt);
const newUser = {
...id,
password: hashedPassword,
email,
};
await users.push(newUser);
await helper.writeJSONFile(filename, users);
return res.status(201).json({
message: `New user was created`,
user: newUser,
originalPassword: password,
hashedPassword,
});
} catch (err) {
res.status(500).json({ message: err.message });
// res.status(500).json({ message: "Mesasge from the catch block" });
}
});
The problem seems to be in my function that looks for a user in the database:
function findUser(array, email) {
return new Promise((resolve, reject) => {
const row = array.find((r) => r.email == email);
if (!row) {
reject({
message: "User not found",
});
reject(null);
}
resolve(row);
});
};
I'm trying to register a new user and I first check if the email already exists in the json
file using the function above:
const user = await helper.findUser(users, email);
However, it seems that if the user is not found, the function call ends and I'm sending back a status code to the client. Is there a problem in the way I'm rejecting the promise? How could I return null
from a promise rejection?
解决方案
拒绝承诺将其标记为拒绝/失败。然后await
关键字将抛出您传递给的任何内容reject(...)
。因此,当找不到用户时,您的代码会异常中止。你应该在你的await helper.findUser(...)
电话周围放一个try/catch。或者,resolve(null)
如果您希望 await 返回 null 而不是抛出,请调用。
这也意味着您不应该调用reject
两次,或者更糟的是,调用这两个reject
并且resolve
与您的代码当前所做的相同。调用其中一个函数并不等同于返回,该函数仍然必须干净地返回。
推荐阅读
- python - Plotly Express 分组小提琴分布未显示
- java - 球衣应用中的 Micrometer Prometheus 指标(非弹簧)
- powerquery - Excel Power Query 合并 - 连接两个表,其中公共字段不是唯一的,并且仅在一个特定列中没有重复值
- django - 我应该如何在 Django 中存储文件
- regex - 在 PCRE 正则表达式支持的编辑器中,从代码文件中替换和/或删除特定 JSON 键值字符串的前 n 次出现
- reactjs - 从 redux 工具包中导出额外的 reducer
- android - Kotlin - 函数的通用绑定
- python - 修改 enum.IntFlag __repr__
- python - 你能在 BeautifulSoup 中找到汤的父代吗
- javascript - 即使我跳到下一个元素,焦点指示器也会停留在无线电输入上