Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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' });
  }
});

>Solution :

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);
      });
  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading