Dave
Dave

Reputation: 19150

In Axios, how do I capture the response error body that the network tab reports?

I’m using axios 0.21.1. When I make a POST request, I get a 400 error, and I can see this response in my dev tools -> network tab's "Response" tab,

{"data":[" value does not allow numbers"]}

How do I capture that error in a variable? I tried this

  axios.post(`/api/myendpoint`,
    { 
      data: 2
    },
    {
      headers: {'ACCEPT': 'application/json'}
    })
    .then(response => {
      …
    })
    .catch(response => {
      console.log(response.data);

But “response.data” prints out “undefined”. I’ve also tried “response.body” but also undefined.

Upvotes: 0

Views: 1642

Answers (2)

Harpreet Singh
Harpreet Singh

Reputation: 979

Catch the error, check the status and use it however you want

 axios.post(`/api/myendpoint`,
{ 
  data: 2
},
{
  headers: {'ACCEPT': 'application/json'}
},
.then(response => {
  …
})
.catch((error) => {
   if (error.response && error.response.status === 400)  {
      let errorVar = error.response.data;
      console.log(errorVar);
   }
});

Upvotes: 0

BraveVN
BraveVN

Reputation: 430

you should catch the error and return the body like this:

.catch(error) => {
  console.log(error.response.data);
}

Details in the Axios document

Upvotes: 0

Related Questions