Axios请求封装

Axios请求封装

  1. 支持 getpost 快捷调用
  2. 支持重复请求取消
  3. 支持通用错误处理
  4. 支持类型推导
import request, { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance, Method } from 'axios';
import { message } from 'antd';
import qs from 'qs';

/**
 * 接口Response出参
 */
export interface IResponse<T = any> {
  flag: 0 | 1;
  data?: T;
  msg?: string;
  code?: string;
}

interface IPending {
  /**
   * 所有请求中对象
   */
  [paramsName: string]: Function;
}

/** 缓存请求url */
let pending: IPending = {};

/** 取消重复请求 */
const removePending = (pending: IPending, config: AxiosRequestConfig): void => {
  let key = `${config.url}&${config.method}`;
  if (pending[key]) {
    pending[key].call(config);
    delete pending[key];
  }
};

const axios = request.create({
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'X-Requested-With': 'XMLHttpRequest'
  }
});

axios.interceptors.request.use(
  (config: AxiosRequestConfig): AxiosRequestConfig => {
    if (config.data instanceof FormData) {
      config.headers['Content-Type'] = 'multipart/form-data';
    } else {
      config.data = qs.stringify(config.data);
    }
    return config;
  },
  (error: AxiosError): Promise<AxiosError> => Promise.reject(error)
);

axios.interceptors.response.use(
  (response: AxiosResponse): AxiosResponse => response,
  (error: AxiosError): Promise<AxiosError> => Promise.reject(error)
);

interface IAxiosStrongArgs {
  /** 请求接口url */
  url: string;
  /** 发送请求的方式,默认为get */
  method?: Method;
  /** 要提交的数据 */
  data?: any;
  /** 是否开启错误自动处理,true为开启,false关闭,默认为true */
  handleErrorAuto?: boolean;
  /** 是否取消重复请求,默认为true */
  cancelRepeatReq?: boolean;
  /** axios请求config */
  reqConfig?: AxiosRequestConfig;
}

/**
 * axios请求包装方法
 * @param args {IAxiosStrongArgs}
 */
const axiosStrong = async <R = any>(args: IAxiosStrongArgs): Promise<IResponse<R>> => {
  const {
    url,
    method = 'get',
    data,
    handleErrorAuto = true,
    cancelRepeatReq = true,
    reqConfig = {}
  } = args;
  /** 构造请求的config内容 */
  let config: AxiosRequestConfig = {
    url,
    method,
    ...reqConfig
  };
  if (cancelRepeatReq) {
    removePending(pending, config);
    config.cancelToken = new request.CancelToken((c: Function) => {
      // 给每个请求加上特定取消请求方法
      pending[`${config.url}&${config.method}`] = c;
    });
  }
  try {
    let { data: response }: AxiosResponse<IResponse<R>> = await axios({
      url,
      method,
      data,
      ...config
    });
    if (response.flag === 0 && handleErrorAuto) {
      // 自动弹出错误提示信息
      message.error(response.msg);
    }
    return response;
  } catch (err) {
    return {
      flag: 0
    };
  }
};

/**
 * 发送get请求
 * @param url 请求url
 * @param config {Partial<IAxiosStrongArgs>}
 */
export const axiosGet = <R = any>(url: string, config: Partial<IAxiosStrongArgs> = {}) => {
  return axiosStrong<R>({
    url,
    ...config
  });
};

/**
 * 发送post请求
 * @param url 请求url
 * @param data 请求数据
 * @param config {Partial<IAxiosStrongArgs>}
 */
export const axiosPost = <R = any>(url: string, data: any, config: Partial<IAxiosStrongArgs> = {}) => {
  return axiosStrong<R>({
    url,
    method: 'post',
    data,
    ...config
  });
};

export default axiosStrong;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值