0

I am doing POST request with invalid data, I do it on purpose, because I am testing response messages from server. When I pass valid data, then everything is ok. Server is built on express.js

Here is my frontend code with axios:

async function submitRegister() {
    try {
      const responseFromServer = await axios.post('http://localhost:5000/register', {
        value1: value1,
        value2: value2,
        value3: value3,
        value4: value4,
        value5: value5
      }, {
        headers: {
          'Content-Type': 'application/json'
        },
        withCredentials: true
      });

      if (responseFromServer.status === 201) {
        console.log(responseFromServer);
      } else {
        console.log(responseFromServer);
      }

    } catch (error) {
      console.log(error);
    }
  }

When status 400 I want get that json response:

if (validationMessage) {
    return res.status(400).json({
        success: false,
        message: validationMessage,
        isLoggedIn: req.session.isLoggedIn
    });
}

But instead I see in console: POST http://localhost:5000/register 400 (Bad Request) Error: Request failed with status code 400

misugi
  • 15
  • 6
  • Have you used curl, postman, or some other tool to test your express endpoint independent of react/axios? – John Sep 17 '21 at 12:01
  • Yes, I see that messages in Postman, but how to get that in Browser? – misugi Sep 17 '21 at 12:05
  • Your react/axios code looks correct to me. Do you see any errors in your express logs when you call the endpoint from the browser? – John Sep 17 '21 at 12:11
  • No errors, everything should works – misugi Sep 17 '21 at 12:32
  • It looks like you may need to get your `error.response.body` as described here: https://stackoverflow.com/questions/45017822/catching-error-body-using-axios-post – John Sep 17 '21 at 12:37
  • 1
    Thanks, I just found this :D – misugi Sep 17 '21 at 12:39
  • Does this answer your question? [catching error body using axios post](https://stackoverflow.com/questions/45017822/catching-error-body-using-axios-post) – John Sep 17 '21 at 12:41
  • Yes, error.response.data.message is what I need ;) – misugi Sep 17 '21 at 12:42

0 Answers0