简体   繁体   English

密码错误时请求被卡住(Async/Await)

[英]Request is stuck when password is wrong (Async/Await)

So,i am quite new to async await.But i thought i should implement it in one of project to see how it really works and understands totally.But i am stuck & not able to understand what really is happening.所以,我对异步等待很陌生。但我认为我应该在一个项目中实现它,看看它是如何真正工作并完全理解的。但我被卡住了,无法理解到底发生了什么。

So in my PERN app, i am trying to log a user, so the request comes from the front end, with username and password, and then i use the findOne(sequelize), method to find if the user exist or not, and also doing the same for the password, but comparing it using bcrypt compare function.所以在我的PERN应用程序中,我试图记录一个用户,所以请求来自前端,带有用户名和密码,然后我使用findOne(sequelize)方法来查找用户是否存在,以及对密码执行相同操作,但使用 bcrypt 比较 function。

But when the user enters a wrong email or password the whole response is stuck somehow,as i am getting a response of 500, though i have handled the error for these kind of events.但是,当用户输入错误的 email 或密码时,整个响应会以某种方式卡住,因为我得到的响应为 500,尽管我已经处理了此类事件的错误。

I am saying it is stuck because i added a console at the bottom of that findOne and compare function, they are not logging, but as soon as the email or password is correct the response is received.我说它卡住了,因为我在 findOne 的底部添加了一个控制台并比较 function,它们没有记录,但只要 email 或密码正确,就会收到响应。

 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,
    });
  }

I think you have a typo (bcypt vc bcrypt):) And I think the method rejects when the fields do not match.我认为您有错字(bcypt vc bcrypt):) 而且我认为当字段不匹配时该方法会拒绝。 So you should wrap the compare in a try/catch block.因此,您应该将比较包装在 try/catch 块中。 Or you could use the sync version或者你可以使用同步版本

bcrypt.compareSync(password, user.password);

which will return true or false这将返回 true 或 false

your code is missing a try catch block to handle errors !您的代码缺少用于处理错误的 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM