kim-request.js 1.78 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
        this.destroy(url);
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
47 48 49
        if (options.successHandler instanceof Function) {
          options.successHandler({ queues: this.queues, res, options });
        }
duanledexianxianxian's avatar
duanledexianxianxian committed
50
        const { data, status } = res;
duanledexianxianxian's avatar
duanledexianxianxian committed
51 52 53 54 55
        return { data, status };
      },
      error => {
        // error
        this.destroy(url);
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
56 57
        if (options.errorHandler instanceof Function) {
          options.errorHandler({ queues: this.queues, error, options });
duanledexianxianxian's avatar
duanledexianxianxian committed
58 59
        }
        return Promise.reject(error);
duanledexianxianxian's avatar
duanledexianxianxian committed
60 61 62 63 64 65 66 67 68 69 70 71
      },
    );
  }

  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;