简体   繁体   English

发布请求失败后不返回错误 - axios, express, node.js

[英]Not returning an error after failed post request - axios, express, node.js

I am trying to implement the validation of password change and the issue I have is that I am not getting errorMessage back from the server in case of an error.我正在尝试实现密码更改的验证,我遇到的问题是如果出现错误,我没有从服务器返回 errorMessage。 I have managed to get it work and send back response after the password was updated.我已经设法让它工作并在密码更新后发回响应。 Also, I can console.log the error message on the back end but it's not returning an object with errorMessage to the front end.此外,我可以在后端控制台记录错误消息,但它不会将带有 errorMessage 的 object 返回到前端。

    if (!currentPassword) {
    console.log("no current password");
    return res
      .status(400)
      .json({ errorMessage: "Please confirm your current password" });
}

On the front code looks like this:前面的代码如下所示:

  handleSubmit = (event) => {
event.preventDefault();
const authorization = localStorage.getItem("accessToken");

axios
  .put(
    `${process.env.REACT_APP_SERVER_URL}/settings/password`,
    this.state.user,
    {
      headers: {
        authorization,
      },
    }
  )
  .then((res) => {
    if (res.errorMessage) {
      console.log(res, "Unsuccessful password updated");
   
    } else {
      console.log("updating - res:", res);
      this.setState({
        user: res.data,
      });
    }
  })

  .catch((err) => {
    console.log(err, "ERROR");
  });
 };

Everytime there is an error, I am not consol login the actual erroMessage but it is being catched in catch.每次出现错误时,我都不会登录实际的 erroMessage,但它会被捕获。 What is the cause of that?这是什么原因?

Thanks谢谢

Not a direct res its available under res.data .不是直接res ,它在res.data下可用。

Response schema of axios axios 的响应模式

use利用

if (res.data.errorMessage) {

instead of代替

if (res.errorMessage) {

For better understanding you need to console.log(res) .为了更好地理解,您需要console.log(res) Then you could understand the structure of the response然后你就可以理解响应的结构了

router.put("/password", isLoggedIn, (req, res, next) => {
  const { currentPassword, newPassword, newPasswordConfirm } = req.body;

 

  User.findById(req.user._id)
    .then((user) => {
      bcrypt.compare(currentPassword, user.password).then((isSamePassword) => {
        if (!isSamePassword) {
          console.log(
            "Incorrect current password. To change your password try again!"
          );
          return res.status(400).json({
            errorMessage:
              "Incorrect current password. To change your password try again!",
          });
        }

        return bcrypt
          .genSalt(saltRounds)
          .then((salt) => bcrypt.hash(newPassword, salt))
          .then((hashedPassword) => {
            User.findByIdAndUpdate(
              req.user._id,
              { password: hashedPassword },
              { new: true }
            )
              .then((user) => {
                console.log("user's password successfully changed");
                res.status(200).json(user);
              })
              .catch((err) => {
                res.status(500).json({ errorMessage: err.message });
              });
          })
          .catch((err) => {
            res.status(500).json({ errorMessage: err.message });
          });
      });
    })
    .catch((err) => {
      console.log(err);
      res.status(500).json({ errorMessage: err.message });
    });
});

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

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