当我们使用Axios时,我们总是必须从响应中获取数据。像这样:
const response = await Axios.get('/url')
const data = response.data
有没有办法让Axios已经返回数据?像这样:
const data = await Axios.get('/url')
除了来自响应的数据之外,我们从未使用过任何东西。
您可以像这样使用ES6破坏:
const { data } = await Axios.get('/url');
这样你就不用再写一行代码了。
添加一个响应拦截器
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response.data; // do like this
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
我通常做的是创建一个名为interceptors.js
的js文件
import axios from 'axios';
export function registerInterceptors() {
axios.interceptors.response.use(
function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response.data;
},
function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
}
);
}
在./src/index.js
中
import { registerInterceptors } from './path/to/interceptors';
registerInterceptors();//this will register the interceptors.
对于最佳实践,不要在任何地方都使用axios
,以防将来如果您想迁移到不同的http
提供程序,则必须在它使用的任何地方进行更改。
创建一个围绕axios的包装器,并在你的应用中使用该包装器
例如:
创建一个名为http.js
的js文件
const execute = ({url, method, params, data}) => {
return axios({
url,
method,//GET or POST
data,
params,
});
}
const get = (url, params) => {
return execute({
url, method: 'GET', params
})
}
const post = (url, data) => {
return execute({
url, method: 'POST', data
})
}
export default {
get,
post,
};
并像一样使用它
import http from './http';
....
http.get('url', {a:1, b:2})
因此,现在您可以在整个应用程序中进行自定义,甚至更改http提供程序也非常简单。