异步bcrypt发布请求未返回响应

问题描述 投票:0回答:1

我正在尝试比较密码以登录用户,但是我不断收到“此请求无响应。”

这是我的张贴路线。

router.route("/login/:username1").post(async (req, res) => {
  const userexist = User.find(username=>userexist.username=req.body.username1)
      if(userexist == null) 
      {
        return res.status(400).json("Cannot find user");
      }
      try 
      {
        if(await bcrypt.compare(req.body.password, userexist.password))
        {
          res.json("success");
        }
        else
        {
          res.json("Not Allowed");
        }
      } catch {
        res.status(500).json();
      }
});

这是我登录页面上的发布方法。

onSubmit(e) {
    e.preventDefault();
    const isValid = this.validate();
    const username1=this.state.username;
    if (isValid) {
      const user = {
        username: this.state.username,
        password: this.state.password,
      };

      axios
      .post("http://localhost:5000/users/login/"+ username1, user)
      .then((res) => console.log(res.data));
      this.setState(initialState);
    }
  }
node.js reactjs mongodb react-router bcrypt
1个回答
-1
投票

进行一些更正,看看你怎么走:

  • 在控制器中使用等待状态
  • 使用下面的代码行,您正在发送用户对象。因此,在您的控制器中,使用req.body.username(而不是req.body.username1)
axios.post("http://localhost:5000/users/login/"+ username1, user)
  • 如代码片段所示,对find功能进行校正
  • 还要检查您的cors并确保客户端遵守服务器cors规则
router.route("/login/:username1").post(async (req, res) => {
    const userexist = await User.find(user=>user.username==req.body.username) //<---- make correction to find method ... use await and use correct req body object i.e. username not username1
        if(userexist == null) 
        {
          return res.status(400).json("Cannot find user");
        }
        try 
        {
          if(await bcrypt.compare(req.body.password, userexist.password))
          {
            res.send("success"); //<----- as best practice, while sending strings just use res.send('success')... res.json is not reqd
          }
          else
          {
            res.send("Not Allowed"); //<----- for strings, it is better to use res.send instead of res.json
          }
        } catch {
          res.status(500).json(); //<----- remember to pass meaningful error message back to client
        }
  });
© www.soinside.com 2019 - 2024. All rights reserved.