mohan m
mohan m

Reputation: 67

Not able to get the response code in react js axios

Here is my common method for post:

export const post = (url: string, param: any) => {
   const CancelToken = axios.CancelToken; // axios cancel request
   const source = CancelToken.source();
   post.prototype.source = source;
   return axios.post(url, qs.stringify(param), { cancelToken: 
   source.token }).then((resp) => resp);
};

Here is my post method:

const postMyMethod = async () => {
    await postMd(params)
    .then((response: any) => {
        console.log(response) // in response not getting status code
    })
};

Below is the error handling code, how to get the response status code(ex: 200, 400...):

axios.interceptors.response.use(
  function (response) {
    if (response && response.data && response.data.Code && response.data.Message) {
      message.error(response.data.Message);
      response.data = null;
    }
    return response;
  },
  function (error) {
    if (error.response && error.response.data && error.response.data.Code && error.response.data.Message) {
      message.error(error.response.data.Message);
    } else {
      message.error('Unknown error, please check your network ~');
    }
    return error;
  }
);

Finally if I do:

console.log(response)

Getting: Error: Request failed with status code 400

How to get the status code to do the if condition in the postMyMethod()?

I want to do like this in the postMyMethod(). How to achieve this?

if(response.status === 200){
// do something
}
if (respone.status === 400){
// do something
}

Upvotes: 5

Views: 2693

Answers (2)

mohan m
mohan m

Reputation: 67

Finally got it:

.then((response: any) => {
    console.log(response.response.status);
    console.log(response.response.data);
})

or need to add below code under function error > if condition

return error.response;

Now getting the response status and failure data.

Upvotes: 0

niiir
niiir

Reputation: 377

The error is because you are not using a catch() block in your postMyMethod function. You should add it so it will handle any error response. It will look something like this:

const postMyMethod = async () => {
    await postMd(params)
    .then((response) => {
        console.log(response)
    }).catch((err) => {
    console.log(err.response.statuscode);
  });
};

If response code 400 is something specific you want to handle differently in your function, your catch() block will be:

const postMyMethod = async () => {
    await postMd(params)
            .then((response) => {
                console.log(response)
            }).catch((err) => {
               if (err.response.statuscode == 400) {
                   console.log(err);
               } else {
                 console.log("something else");
               }
            });
        };

You can read more about the catch() method here.

Upvotes: 1

Related Questions