【问题标题】:Change axios Response Schema更改 axios 响应模式
【发布时间】:2020-02-19 05:26:03
【问题描述】:

正如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

【问题讨论】:

    标签: vue.js xmlhttprequest axios


    【解决方案1】:

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

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

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

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

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

    更新:

    如果您需要访问successmessagedata,您只需要这个:

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

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

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

    【讨论】:

    • 我知道响应拦截器,但我也需要来自实际响应的其他道具,不能简单地丢弃 API 的一半响应。这就是为什么标题说 change **axios** response schema 而不是 API 的响应。
    • @SyedAliTaqi 我不完全按照你的要求,但我仍然相信响应拦截器是答案。也许你只需要return response.data?您能否更新问题以包含您想要的示例?
    • 我不希望 axios 将实际 API 响应包装到自定义对象中。
    • @SyedAliTaqi 您能否说明这与在拦截器中使用return response.data 有何不同?这样做你会得到一个具有successmessagedata 属性的对象,这似乎是你想要的。如果这不是您所要求的,那么如果您可以更新问题以提供对您想要的内容的清晰完整的描述,那将非常有帮助。目前它只是询问如何避免.data.data,但没有具体说明您想要什么。
    • 道歉,我的错!我把interceptorstransformResponse 钩子弄混了,因为我试过了,它没有用。请仔细阅读您的评论,让我尝试使用拦截器...
    猜你喜欢
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 2015-08-28
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多