简体   繁体   中英

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. 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.

    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. What is the cause of that?

Thanks

Not a direct res its available under res.data .

Response schema of axios

use

if (res.data.errorMessage) {

instead of

if (res.errorMessage) {

For better understanding you need to 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 });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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