why does 400 status code result always entercatch block execution with axios?

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error why does 400 status code result always entercatch block execution with axios? on this date .

I have a contact me form in my frontend with three fields -> name, email, message. which are being passed to backend using axis

if the user doesn’t enter any of the one value, it should show “please fill all the details” which is coming from backend. But here in my case in browser console.log i am seeing this error

POST https:/api-endpoint/contactMe 400

try-catch block catch error:

    Error: Request failed with status code 400
        at createError (createError.js:16:1)
        at settle (settle.js:17:1)
        at XMLHttpRequest.handleLoad (xhr.js:62:1)

If all the fields are entered it results in successful message from backend which is “thank you for contacting jatin” – this works perfectly well

Why 200 status code msg from backend is working and why 400 status code msg from backend results in error? Is this an issue with axios that for 400 or error status code it will raise exception?

Here is my react code

const handleName = (e) => {
    setName(e.target.value);
  };
  const handleEmail = (e) => {
    setEmail(e.target.value);
  };
  const handleMessage = (e) => {
    setMessage(e.target.value);
  };
  const submitForm = async (e) => {
    e.preventDefault();
    try {
      let data = {
        name,
        email,
        message,
      };
      setBool(true);
      console.log(data);
      const res = await axios.post(
        'https:/api-endpoint/contactMe',
        data
      );
      console.log(res);
      if (name.length === 0 || email.length === 0 || message.length === 0) {
        console.log('hihi');
        setBanner(res.data.msg);
        toast.error(res.data.msg);
        setBool(false);
      } else if (res.status === 200) {
        setBanner(res.data.msg);
        toast.success(res.data.msg);
        setBool(false);

        setName('');
        setEmail('');
        setMessage('');
      }
    } catch (error) {
      console.log(error);
    }
  };

my backend route

app.post('/contactMe', async (req, res, next) => {
  const data = req.body;
  if (
    data.name.length < 1 ||
    data.email.length < 1 ||
    data.message.length < 1
  ) {
    return res.status(400).json({ msg: 'Please fill all the fields' });
  }

  const params = {
    Destination: {
      ToAddresses: ['reciever@gmail.com'],
    },
    Message: {
      Body: {
        Text: { Data: `${data.message}` },
      },

      Subject: {
        Data: `Hiring interest from "${data.name}" : "${data.email}"`,
      },
    },
    Source: 'sender@gmail.com',
  };
  try {
    const data = await ses.sendEmail(params).promise();
    console.log(data);
    return res.status(200).json({ msg: 'Thank you for contacting Jatin!!!' });
  } catch (error) {
    console.log(error);
    return res.status(500).json({ msg: 'Service Unavailable' });
  }
});

Answer

Perhaps this approach might help you?

const handleName = (e) => {
    setName(e.target.value);
  };
  const handleEmail = (e) => {
    setEmail(e.target.value);
  };
  const handleMessage = (e) => {
    setMessage(e.target.value);
  };
  const submitForm = async (e) => {
    e.preventDefault();
      let data = {
        name,
        email,
        message,
      };
      setBool(true);
      console.log(data);
      const res = await axios.post(
        'https:/api-endpoint/contactMe',
        data
      ).then(res => { // Response handler
        console.log(res);
        setBanner(res.data.msg);
        toast.success(res.data.msg);
        setBool(false);

        setName('');
        setEmail('');
        setMessage('');
      }).catch(error => { // Error handler
        console.log(error);
        setBanner(error.response.data.msg);
        toast.error(error.response.data.msg);
        setBool(false);
      });
  };