gpt4 book ai didi

vue.js - 更改 axios 响应架构

转载 作者:行者123 更新时间:2023-12-04 17:30:21 26 4
gpt4 key购买 nike

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每次?

最佳答案

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

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

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

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

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

更新:

如果您需要访问 success , messagedata你只需要这个:

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

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

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

});

关于vue.js - 更改 axios 响应架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60293587/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com