【问题标题】:Request is stuck when password is wrong (Async/Await)密码错误时请求被卡住(Async/Await)
【发布时间】:2020-07-26 03:07:05
【问题描述】:

所以,我对异步等待很陌生。但我认为我应该在一个项目中实现它,看看它是如何真正工作并完全理解的。但我被卡住了,无法理解到底发生了什么。

所以在我的PERN应用程序中,我试图记录一个用户,所以请求来自前端,带有用户名和密码,然后我使用 findOne(sequelize), 方法来查找用户是否存在, 对密码也做同样的事情,但使用 bcrypt 比较函数进行比较。

但是当用户输入错误的电子邮件或密码时,整个响应会以某种方式被卡住,因为我得到了 500 的响应,尽管我已经处理了此类事件的错误。

我是说它卡住了,因为我在 findOne 和比较功能的底部添加了一个控制台,它们没有记录,但只要电子邮件或密码正确,就会收到响应。

 const { email, password } = req.body;

  console.log({ email, password });

  const user = await User.findOne({ where: { email } });

  const passwordMatch = await bcyptjs.compare(password, user.password);
  console.log('Cant Reach here when the fields are incorrect', password);
  console.log('Cant Reach here when the fields are incorrect', user.password);


  if (!user &&  !passwordMatch) {
    return next({
      message: 'Username or Password is incorrect.',
      statusCode: 400,
    });
  }

【问题讨论】:

  • 是否有任何未处理的 Promise 拒绝退出?
  • 应该是 if (!user || !passwordMatch) {
  • 我以某种方式修复了它,我所做的是我在检查用户后添加了!用户,密码也是如此,同时检查两者都不起作用,不知道为什么,奇怪的是,我在猫鼬中做了同样的事情,而且效果很好..

标签: javascript node.js express


【解决方案1】:

我认为你有一个错字(bcypt vc bcrypt):) 而且我认为当字段不匹配时该方法会拒绝。因此,您应该将比较包装在 try/catch 块中。 或者你可以使用同步版本

bcrypt.compareSync(password, user.password);

这将返回真或假

【讨论】:

  • 我认为这不是问题,因为导入的名称是相同的,虽然我更改了它但仍然没有运气,并且为了处理错误我有异步处理程序中间件,asyncCatch = (fn) = > (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
【解决方案2】:

您的代码缺少用于处理错误的 try catch 块!

    const { email, password } = req.body;
    
      console.log({ email, password });

     try{

      const user = await User.findOne({ where: { email } });
    
      const passwordMatch = await bcyptjs.compare(password, user.password);
      console.log('Cant Reach here when the fields are incorrect', password);
      console.log('Cant Reach here when the fields are incorrect', user.password);
    
    }catch(e){
    console.log(e.message)
    console.log(e.statusCode)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2018-02-09
    • 2018-01-16
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    相关资源
    最近更新 更多