介绍

基于Promise,用于Node.js和浏览器的http库

Api

restFul风格的api

axios.get();
axios.post();
axios.options();
axios.put();

axios.create();
axios(config);
axios.all([]);

拦截器

  1. // 请求拦截
  2. axios.interaceptors.request.use(config => {
  3. let token = localStorage.getItem('token');
  4. config.header.AuthToken = token;
  5. return config;
  6. }, err => {
  7. })
  8. // 响应拦截
  9. axios.interaceptors.response.use(response => {
  10. return response;
  11. }, err => {
  12. })

axios的封装

  • class封装 ```vue

class request { constructor() { this.config = { baseURL: ‘https://forguo.cn‘, timeout: 10000, }; }

  1. request(options) {
  2. const config = Object.assign({}, this.config, options);
  3. const instance = axios.create();
  4. this.setInterceptors(instance);
  5. return instance(config); // 返回axios实例的执行结果
  6. }
  7. setInterceptors(instance) {
  8. instance.interceptors.request.use((config) => {
  9. return config;
  10. }, err => {
  11. return Promise.reject(err);
  12. });
  13. instance.interceptors.response.use((data) => {
  14. return Promise.resolve(data.data);
  15. }, (err) => {
  16. return Promise.resolve(err);
  17. })
  18. }

}

  1. - axios实例
  2. ```vue
  3. // 创建一个 axios 实例
  4. const request = axios.create({
  5. baseURL: Setting.apiBaseURL,
  6. timeout: 60000 // 请求超时时间
  7. });
  8. // 拦截器
  9. request.interceptors.request.use(config => {}, err => {});
  10. request.interceptors.response.use(response => {}, err => {});