更改axios响应架构 [英] Change axios Response Schema
问题描述
axios GitHub 页面指出,axios请求的默认响应为:>
{//`data`是服务器提供的响应数据: {},//`status`是服务器响应中的HTTP状态代码状态:200,//`statusText`是服务器响应中的HTTP状态消息statusText:确定",//`headers`服务器响应的标题//所有标题名称均小写标头:{},//`config`是为请求提供给`axios`的配置配置:{},//`request`是生成此响应的请求//这是node.js中的最后一个ClientRequest实例(在重定向中)//和浏览器中的XMLHttpRequest实例要求: {}}
问题:
我的API响应架构为:
{成功:对,信息: '',数据: {}}
因此,每次我提出请求时,我都必须像这样处理响应:
(...).then((res)=> res.data.data);
如何更改axios的响应模式以避免每次都执行 .data.data
?
您可以使用响应拦截器来更改promise的值:
axios.interceptors.response.use(function(response){返回response.data.data})
您只需执行一次,然后该操作就会应用于通过默认 axios
实例发出的所有请求.如果使用 axios.create
创建自己的 axios
实例,则可以采用类似的方法.
您可能还需要考虑如何处理错误情况,但是方法大体相同.
文档: https://github.com/axios/axios#interceptors >
更新:
如果您需要访问成功
,消息
和 data
,则只需要以下内容:
axios.interceptors.response.use(function(response){返回response.data})
在编写 then
处理程序时,解构可能会很有用:
(...).then(({{data,success,message})=> {});
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?
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 }) => {
});
这篇关于更改axios响应架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!