Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change axios Response Schema

As axios GitHub page states, default response of axios request is:

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}

Problem:

My API response schema is:

{
  success: true,
  message: '',
  data: {}
}

So every time I make a request, I have to handle the response like:

(...).then((res) => res.data.data);

How can I change the response schema of axios to avoid doing .data.data every time?

like image 537
Syed Ali Taqi Avatar asked Sep 13 '25 02:09

Syed Ali Taqi


1 Answers

You can use a response interceptor to change the value of the promise:

axios.interceptors.response.use(function (response) {
  return response.data.data
})

You'd just do this once and then it would apply to all requests made via the default axios instance. A similar approach can be taken if you're creating your own axios instances using axios.create.

You may also need to consider how to handle error cases but the approach is much the same.

Documentation: https://github.com/axios/axios#interceptors

Update:

If you need access to success, message and data you would just need this instead:

axios.interceptors.response.use(function (response) {
  return response.data
})

Destructuring would potentially be useful when you write the then handler:

(...).then(({ data, success, message }) => {

});
like image 126
skirtle Avatar answered Sep 15 '25 01:09

skirtle