问题
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?
回答1:
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 }) => {
});
来源:https://stackoverflow.com/questions/60293587/change-axios-response-schema