【问题标题】:Hashing password not working after using await使用等待后哈希密码不起作用
【发布时间】:2021-08-28 04:54:05
【问题描述】:

我在更新密码后尝试对密码进行哈希处理,但我不明白为什么它只是在等待行之后才起作用。在 res.json 中,我得到了散列密码,但就在那里。 我是新手,所以我很感激任何帮助或建议。

router.put('/:id', async (req, res) => {
let { mail, password } = req.body;

bcrypt.genSalt(saltRounds, function (err, salt) {
if (err) return next(err);

bcrypt.hash(password, salt, function (err, hash) {
  if (err) return next(err);
  password = hash;
});
});

const newUser = { mail, password };
await User.findByIdAndUpdate(req.params.id, newUser);
res.json({ mensaje: `Updated Password ${password}` });
});

【问题讨论】:

  • 您需要查看异步/等待和回调。您在这里混合,调用 crypt.genSalt 和 bcrypt.hash 的回调不会按顺序触发。您应该考虑将 bcrypt 实现移动到 Promise 并使用 async/await 或将 newUser 行移动到 bcrypt.hash 回调中
  • 谢谢,这对我有用 我将 newUser 行移到哈希函数中并使其异步

标签: node.js api rest bcrypt


【解决方案1】:

根据我的评论,您应该更多地研究 async/await 和回调以了解调用顺序。因为它不是以您认为的顺序方式运行的。但您可以尝试以下方法。

router.put('/:id', async (req, res) => {
  let { mail, password } = req.body;
  try{
    const salt = await bcrypt.genSalt(saltRounds);
    const hashedPassword = await bcrypt.hash(password, salt);
    const newUser = { mail, password };
    await User.findByIdAndUpdate(req.params.id, newUser);
    res.json({ mensaje: `Updated Password ${password}` });
  } catch(error) {
    res.json(error);
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 2021-10-03
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    相关资源
    最近更新 更多