根据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
?
答案 0 :(得分:1)
您可以使用响应拦截器来更改Promise的值:
axios.interceptors.response.use(function (response) {
return response.data.data
})
您只需执行一次,然后该操作便会应用于通过默认axios
实例发出的所有请求。如果您使用axios
创建自己的axios.create
实例,则可以采用类似的方法。
您可能还需要考虑如何处理错误情况,但是方法大体相同。
文档:https://github.com/axios/axios#interceptors
更新:
如果您需要访问success
,message
和data
,则只需要它:
axios.interceptors.response.use(function (response) {
return response.data
})
编写then
处理程序时,解构可能会很有用:
(...).then(({ data, success, message }) => {
});