[Fixed] res.status(400) makes my chained res.send("this message") not show up on client side

Issue

I’v got this issue where I’m trying to use my Node.js server to answer res.status(400).send("message").

If I remove the res.status, the "message" comes through to my client side. As soon as I add the .status(400), the send part is not included.

Client side

const handleSubmit = (e) => {
    e.preventDefault();
    const data = {
      user: userName,
      email: email,
      password: password,
    };

    axios
      .post("http://localhost:4040/register", data)
      .then((res) => console.log(res))
      .catch((err) => console.log(err));
  };

Server side

exports.registerUser = async (req, res, next) => {
  //Validater user data
  const { error } = registerValidation(req.body);
  if (error) return res.status(400).send(error.details[0].message);
  //Check for existing user
  const emailExist = await User.findOne({ email: req.body.email });
  if (emailExist) return res.status(400).send("email already in use");

  //Hashing password
  const hashedPassword = await bcrypt.hash(req.body.password, 10);

  //Upload to database
  const user = new User({
    user: req.body.user,
    email: req.body.email,
    password: hashedPassword,
  });
  try {
    await user.save();
    res.send("User created");
  } catch (err) {
    console.log(err);
    res.status(400).send(err);
  }
};

Any ideas why my message is removed when a status code is also included?

Best regards,
Oscar

Solution

When you add status 400 it will go to the catch block with axios and when removing the status it will be considered as 200 by default

so you need to handle the message on the catch block of the axios when the status is 400 by reading err.response.data

check the documentation on how axios handles errors and statuscode that falls out of the range of 2xx

Leave a Reply

(*) Required, Your email will not be published