【问题标题】:UnhandledPromiseRejectionWarning when using bcrypt on Mongoose Method在 Mongoose 方法上使用 bcrypt 时出现 UnhandledPromiseRejectionWarning
【发布时间】:2021-09-26 04:10:45
【问题描述】:

尝试实施重置密码功能,但这样做时不断收到UnhandledPromiseRejectionWarning: Error: Illegal arguments: undefined, string 错误。我在其他项目中使用过这段代码,它完美无瑕,但由于某种原因,我似乎无法弄清楚为什么它会不断弹出或下面的代码可能有什么问题..

方法:

UserSchema.methods.hashPassword = () => {
  return new Promise((resolve, reject) => {
    bcrypt.genSalt(10, (err1, salt) => {
      if (err1) {
        reject(err1);
      }
      bcrypt.hash(this.password, salt, (err2, hash) => { // <-- it appears to happen on this line at ".hash"
        if (err2) {
          reject(err2);
        }
        this.password = hash;
        resolve(hash);
      });
    });
  });
};

路线:

const resetPassword = async (req, res) => {

      // Update User
      const { password } = req.body;
      user.password = password;
      user.passwordResetToken = '';
      user.passwordResetExpires = moment().utcOffset(0);

      user.hashPassword().then(() => { <---- Happens here
        // Save Updated User to the Database
        user.save((error) => {
          if (error) {
            return res.status(500).json({
              success: false,
              message: 'An unexpected error occurred.',
            });
          }

          // Send Email Confirming Password Change to the User
          
        });
      });
    });
  });
};

【问题讨论】:

  • 可能会回调。并返回完成会解决这个问题?

标签: node.js express mongoose bcrypt


【解决方案1】:

bcrypt 也不适用于我,但 bcryptjs 可以。删除 bcrypt 后尝试导入“bcryptjs”。

您可以从 https://www.npmjs.com/package/bcryptjs 下载它。

然后将其导入您的文件并重试。

【讨论】:

  • 我建议您尝试通过代码示例而不是链接来阐明您的答案
猜你喜欢
  • 1970-01-01
  • 2021-08-05
  • 2019-08-17
  • 2019-04-26
  • 2022-09-24
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 2019-03-11
相关资源
最近更新 更多