更改axios响应架构

时间:2020-02-19 05:26:03

标签: vue.js xmlhttprequest axios

根据axios GitHub页的说明,axios请求的默认响应为:

{
  // `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: {}
}

问题:

我的API响应架构为:

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

因此,每次我提出请求时,我都必须像以下那样处理响应:

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

如何更改axios的响应模式以避免每次都.data.data

1 个答案:

答案 0 :(得分:1)

您可以使用响应拦截器来更改Promise的值:

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

您只需执行一次,然后该操作便会应用于通过默认axios实例发出的所有请求。如果您使用axios创建自己的axios.create实例,则可以采用类似的方法。

您可能还需要考虑如何处理错误情况,但是方法大体相同。

文档:https://github.com/axios/axios#interceptors

更新

如果您需要访问successmessagedata,则只需要它:

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

编写then处理程序时,解构可能会很有用:

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

});