基于类封装axios

 

import Axios from 'ts-axios-ttn';
import Store from '../store/index';
import { Message } from 'element-ui';
import { getToken, removeToken } from './auth';
// import router from '../router';
const tokenHeaderName = 'x-auth-token';

const CancelToken = Axios.CancelToken;
// const cancelList = [];
const source = CancelToken.source();

Axios.interceptors.request.use(
  config => {
    config.headers[tokenHeaderName] = getToken();
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

export default class CommonInterface {
  static fetch = (
    url = '',
    method = 'get',
    data = {},
    baseUrl = '',
    isSuccessMessage = false,
    isErrorMessage = true,
    callback = null
  ) => {
    const toMethod = method.toLocaleLowerCase();
    if (['form', 'formpost'].includes(toMethod)) {
      Store.dispatch('asyncFullScreenLoading', true);
    }
    const baseConfig = {
      baseURL: baseUrl ? window.$apiUrl + baseUrl : window.$apiUrl + '/',
      responseType: method === 'download' ? 'blob' : 'json',
      // withCredentials: true,
      headers: {
        'Content-Type':
          toMethod === 'formpost' ? 'multipart/form-data' : 'application/json'
        // 'Access-Control-Request-Headers': '*',
        // Origin: '*'
      }
    };
    baseConfig['headers'][tokenHeaderName] = getToken();
    const config = callback
      ? Object.assign({}, baseConfig, {
          onUploadProgress: progressEvent => {
            if (progressEvent.lengthComputable) {
              callback(progressEvent);
              // 属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
              // 如果lengthComputable为false,就获取不到progressEvent.total和progressEvent.loaded
              // var complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%';
              // console.log(complete);
            }
          }
        })
      : baseConfig;

    const interfaceSign = url.indexOf('?') > -1 ? '&' : '?';
    const interfaceUrl =
      url + interfaceSign + 'timestamp=' + new Date().getTime();

    let instance = Axios.create(config);
    instance = ['get', 'download'].includes(toMethod)
      ? instance.get(interfaceUrl, {
          params: data,
          // cancelToken: new CancelToken(function executor(c) {
          //   cancelList.push(c);
          // })
          cancelToken: source.token
        })
      : toMethod === 'delete'
      ? instance.delete(interfaceUrl, {
          params: data,
          // cancelToken: new CancelToken(function executor(c) {
          //   cancelList.push(c);
          // })
          cancelToken: source.token
        })
      : toMethod === 'formpost'
      ? instance.post(interfaceUrl, data, {
          // cancelToken: new CancelToken(function executor(c) {
          //   cancelList.push(c);
          // })
          cancelToken: source.token
        })
      : instance[toMethod](interfaceUrl, data, {
          // cancelToken: new CancelToken(function executor(c) {
          //   cancelList.push(c);
          // })
          cancelToken: source.token
        });

    return new Promise((resolve, reject) => {
      return instance
        .then(res => {
          if (toMethod !== 'download') {
            const { data, message } = res;
            // const resData = data.data || data;
            const resData = data;
            resolve(resData);
            isSuccessMessage &&
              Message({
                message: message || res.data.message || res.data.msg,
                type: 'success'
              });
          } else {
            const { data, headers } = res;
            const fileName = decodeURI(
              headers['content-disposition']
                .split('filename=')[1]
                .replace(/"/g, '')
            );
            if (
              navigator.userAgent.indexOf('Edge') > -1 ||
              navigator.userAgent.indexOf('NET') > -1
            ) {
              let type = data['type'];
              let blob = new Blob([data], {
                type: type
              });
              if (window.navigator.msSaveBlob) {
                window.navigator.msSaveBlob(blob, fileName);
              }
            } else {
              let url = window.URL.createObjectURL(new Blob([data]));
              let link = document.createElement('a');
              link.style.display = 'none';
              link.href = url;
              link.setAttribute('download', fileName);
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
            }
          }
        })
        .catch(err => {
          reject(err);
          const { code, message } = err || err.data || err.response.data;
          if (code === 403) {
            removeToken();
            // router.replace({
            //   path: '/login'
            // });
          }
          isErrorMessage &&
            Message({
              message: message || err,
              type: 'error'
            });
        })
        .finally(() => {
          Store.dispatch('asyncFullScreenLoading', false);
        });
    });
  };
  constructor(baseUrl, callback) {
    this.baseUrl = baseUrl;
    this.callback = callback;
  }
  get(url, data, isSuccessMessage, isErrorMessage) {
    return CommonInterface.fetch(
      url,
      'get',
      data,
      this.baseUrl,
      isSuccessMessage,
      isErrorMessage,
      this.callback
    );
  }
  post(url, data, isSuccessMessage, isErrorMessage) {
    return CommonInterface.fetch(
      url,
      'post',
      data,
      this.baseUrl,
      isSuccessMessage,
      isErrorMessage,
      this.callback
    );
  }
  formPost(url, data, isSuccessMessage, isErrorMessage) {
    let postData = new FormData();
    if (Object.prototype.toString.call(data) === '[object Object]') {
      for (const key in data) {
        const val = data[key];
        if (val || val === 0 || val === false) {
          postData.append(key, val);
        }
      }
    } else {
      postData = data;
    }
    return CommonInterface.fetch(
      url,
      'formPost',
      postData,
      this.baseUrl,
      isSuccessMessage,
      isErrorMessage,
      this.callback
    );
  }
  put(url, data, isSuccessMessage, isErrorMessage) {
    return CommonInterface.fetch(
      url,
      'put',
      data,
      this.baseUrl,
      isSuccessMessage,
      isErrorMessage,
      this.callback
    );
  }
  patch(url, data, isSuccessMessage, isErrorMessage) {
    return CommonInterface.fetch(
      url,
      'patch',
      data,
      this.baseUrl,
      isSuccessMessage,
      isErrorMessage,
      this.callback
    );
  }
  delete(url, data, isSuccessMessage, isErrorMessage) {
    return CommonInterface.fetch(
      url,
      'delete',
      data,
      this.baseUrl,
      isSuccessMessage,
      isErrorMessage,
      this.callback
    );
  }
  download(url, data, isSuccessMessage, isErrorMessage) {
    return CommonInterface.fetch(
      url,
      'download',
      data,
      this.baseUrl,
      sSuccessMessage,
      isErrorMessage,
      this.callback
    );
  }
  all(list, callback) {
    const axiosList = list.map(item => {
      const { url, method } = item;
      return Axios[method](url);
    });
    Axios.all(axiosList).then(
      Axios.spread(function() {
        callback(Array.from(arguments));
      })
    );
  }
  cancelToken() {
    // for (let i = 0; i < cancelList.length; i++) {
    //   cancelList[i]();
    // }
    source.cancel();
  }
}


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值