kim-request.js 1.58 KB
Newer Older
duanledexianxianxian's avatar
duanledexianxianxian committed
1 2 3 4 5 6 7 8 9 10
import axios from 'axios';

class HttpRequest {
  constructor(options) {
    this.options = options;
    this.queues = {};
  }

  getInsideConfig() {
    const config = {
duanledexianxianxian's avatar
duanledexianxianxian committed
11 12 13 14
      baseURL: this.options.baseUrl, // baseURL
      timeout: 10000,
      responseType: 'json',
      withCredentials: false, // default
duanledexianxianxian's avatar
duanledexianxianxian committed
15 16
      headers: {
        'Access-Control-Allow-Origin': '*',
duanledexianxianxian's avatar
duanledexianxianxian committed
17
        'Content-Type': 'application/json',
duanledexianxianxian's avatar
duanledexianxianxian committed
18
        Accept: 'application/json',
duanledexianxianxian's avatar
duanledexianxianxian committed
19
        'X-Requested-With': 'XMLHttpRequest',
duanledexianxianxian's avatar
duanledexianxianxian committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
        ...this.options.headers,
      },
    };
    return config;
  }

  destroy(url) {
    delete this.queues[url];
  }

  interceptors(instance, url, options) {
    // 请求拦ζˆͺ
    instance.interceptors.request.use(
      config => {
        this.queues[url] = true;
        if (options.beforeRequest instanceof Function) {
          options.beforeRequest({ queues: this.queues, config, options });
        }
        return config;
      },
      error => Promise.reject(error),
    );
    // 响应拦ζˆͺ
    instance.interceptors.response.use(
      res => {
duanledexianxianxian's avatar
duanledexianxianxian committed
45
        // success
duanledexianxianxian's avatar
duanledexianxianxian committed
46 47
        this.destroy(url);
        const { data, status } = res;
duanledexianxianxian's avatar
duanledexianxianxian committed
48 49 50 51 52 53 54 55 56
        return { data, status };
      },
      error => {
        // error
        this.destroy(url);
        if (error.response) {
          console.log(error.response);
        }
        return Promise.reject(error);
duanledexianxianxian's avatar
duanledexianxianxian committed
57 58 59 60 61 62 63 64 65 66 67 68
      },
    );
  }

  request(options) {
    const instance = axios.create();
    const ops = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance, ops.url, ops);
    return instance(ops);
  }
}
export default HttpRequest;