axios和fetch的封装


2019-8-31 vue

axios的封装

import axios from 'axios';

class HttpRequest {
  getInsideConfig() {
    return {
      headers: {
        //
      },
    };
  }

  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use((config) => {
      const newConfig = { ...config };
      // console.log('OUTPUT: HttpRequest -> config', config);

      return newConfig;
    }, error => Promise.reject(error));
    // 响应拦截
    instance.interceptors.response.use((res) => {
      // 判断状态码

      return res;
    }, error => Promise.reject(error));
  }

  get(url, data = { params: {} }) {
    return this.request({
      url,
      method: 'get',
      params: data.params,
    });
  }

  post(url, data) {
    return this.request({
      url,
      method: 'post',
      data,
      timeout: 8000,
    });
  }

  request(options) {
    const instance = axios.create();
    instance.defaults.timeout = 10000;
    const newOptions = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance, newOptions.url);
    return instance(newOptions);
  }
}

export default HttpRequest;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
45
46
47
48
49
50
51
52
53
54

fetch的封装

function buildQuery(obj) {
  const _ = encodeURIComponent;
  return Object.keys(obj).map(k => `${_(k)}=${_(obj[k])}`).join('&');
}

class Req {
  httpDone(res) {
    if (!res.err_code) {
      return res;
    }
    return Promise.reject(res);
  }

  httpFail(err) {
    return Promise.reject(err);
  }

  fetch({
    url, query, data, headers, method = 'GET',
  }) {
    if (query) {
      url += `?${buildQuery(query)}`;
    }
    const params = {
      url,
      method,
      credentials: 'same-origin',
    };
    if (data) {
      params.body = JSON.stringify(data);
    }
    if (headers) {
      params.headers = headers;
    }
    return fetch(url, params)
      .then(resp => (resp.ok ? resp.json().then(this.httpDone) : this.httpFail(resp)))
      .catch(err => Promise.reject(err));
  }

  get(url, params = {}) {
    params.url = params.url || url;
    return this.fetch(params);
  }

  post(url, params = {}) {
    params.url = params.url || url;
    params.method = 'POST';
    return this.fetch(params);
  }
}

export default Req;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
45
46
47
48
49
50
51
52

特别鸣谢

Thomas: 10/11/2019, 3:14:55 PM