介绍
基于Promise,用于Node.js和浏览器的http库
Api
restFul风格的api
axios.get();
axios.post();
axios.options();
axios.put();
…
axios.create();
axios(config);
axios.all([]);
拦截器
// 请求拦截
axios.interaceptors.request.use(config => {
let token = localStorage.getItem('token');
config.header.AuthToken = token;
return config;
}, err => {
})
// 响应拦截
axios.interaceptors.response.use(response => {
return response;
}, err => {
})
axios的封装
- class封装 ```vue
class request { constructor() { this.config = { baseURL: ‘https://forguo.cn‘, timeout: 10000, }; }
request(options) {
const config = Object.assign({}, this.config, options);
const instance = axios.create();
this.setInterceptors(instance);
return instance(config); // 返回axios实例的执行结果
}
setInterceptors(instance) {
instance.interceptors.request.use((config) => {
return config;
}, err => {
return Promise.reject(err);
});
instance.interceptors.response.use((data) => {
return Promise.resolve(data.data);
}, (err) => {
return Promise.resolve(err);
})
}
}
- axios实例
```vue
// 创建一个 axios 实例
const request = axios.create({
baseURL: Setting.apiBaseURL,
timeout: 60000 // 请求超时时间
});
// 拦截器
request.interceptors.request.use(config => {}, err => {});
request.interceptors.response.use(response => {}, err => {});