ts - axios封装

434 阅读2分钟

axios封装

  • 请求配置
  • 请求拦截
  • 响应拦截
  • 单个请求取消
  • 取消所有请求
  • 请求封装
/**axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import axios from "axios";
import type { AxiosRequestConfig } from "axios";
// 环境的切换
// if (process.env.NODE_ENV === 'debug') {
//     axios.defaults.baseURL = "your.globalUrl"
// } else if (process.env.NODE_ENV === 'production') {
//     axios.defaults.baseURL = "your.globalUrl"
// }
axios.defaults.baseURL = "/";
// 请求超时时间
axios.defaults.timeout = 120000; //2分钟

// post请求头
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8";

// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    config.cancelToken = new cancelToken((c) => {
      addPending(config, c);
    });
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  // 服务器状态码不是200的情况
  (error) => {
    console.log(error);
    if (error === "Error: Network Error") {
      alert("网络错误,请检查网络连接");
    } else if (error.response && error.response.status) {
      switch (error.response.status) {
        case 500:
          alert("请求不存在-500");
          break;
        case 404:
          alert("请求不存在-404");
          break;
        // 其他错误,直接抛出错误提示
        default:
          alert("其他错误,请检查网络");
          break;
      }
    }
    return Promise.reject(error.response);
  }
);
let pending: any[] = [];
let cancels: any[] = [];
const cancelToken = axios.CancelToken; // 初始化取消请求的构造函数
const addPending = (config: any, fn?: any) => {
  if (pending.includes(config.url)) {
    let index = pending.indexOf(config.url);
    cancels.splice(index, 1, fn);
  } else {
    if (fn) {
      pending.push(config.url);
      cancels.push(fn);
    }
  }
};
/**
 * @param url 请求地址
 * @param cancelMsg  取消提示信息
 */
export function cancelApi(url: string, cancelMsg?: string) {
  if (pending.includes(url)) {
    let index = pending.indexOf(url);
    pending.splice(index, 1);
    let cancel = cancels.splice(index, 1)[0];
    cancelMsg ? cancel(cancelMsg) : cancel();
  }
}
// 取消所有请求
export function cancelAllApi() {
  pending = [];
  cancels.forEach((cancel) => cancel());
  cancels = [];
}
// 请求类型
export enum Method {
  get = "get",
  GET = "GET",
  delete = "delete",
  DELETE = "DELETE",
  head = "head",
  HEAD = "HEAD",
  options = "options",
  OPTIONS = "OPTIONS",
  post = "post",
  POST = "POST",
  put = "put",
  PUT = "PUT",
  patch = "patch", //更新
  PATCH = "PATCH", //更新
  purge = "purge", 
  PURGE = "PURGE",
  link = "link",
  LINK = "LINK",
  unlink = "unlink",
  UNLINK = "UNLINK",
}
// 封装基础请求
export function baseHttp(
  url: string,
  method: Method,
  config: AxiosRequestConfig & any
) {
  config.url = url;
  config.method = method;
  if (config.url?.indexOf("/") != 0) {
    config.url = "/" + config.url;
  }
  config.url = config.url.replace(/\/\//gi, "/");
  let sendConfig: object = {
    data: config.data ? config.data : config.params,
    params: config.params ? config.params : config.data,
  };
  sendConfig = Object.assign(config, sendConfig);
  return new Promise((resolve, reject) => {
    axios(sendConfig)
      .then((res) => resolve(res.data))
      .catch((e) => reject(e))
      .finally(() => {
        cancelApi(config.url);
      });
  });
}
// 封装成常用的Get请求
export let get = (url: string, config: AxiosRequestConfig & any = {}) => {
  return baseHttp(url, Method.GET, config);
};
// 封装成常用的Post请求
export function post(url: string, config: AxiosRequestConfig & any = {}) {
  return baseHttp(url, Method.POST, config);
}
// 封装成常用的Put请求
export function put(url: string, config: AxiosRequestConfig & any = {}) {
  return baseHttp(url, Method.PUT, config);
}
// 封装成常用的Del请求
export function del(url: string, config: AxiosRequestConfig & any = {}) {
  return baseHttp(url, Method.DELETE, config);
}
// 封装成常用的Patch请求
export function patch(url: string, config: AxiosRequestConfig & any = {}) {
  return baseHttp(url, Method.PATCH, config);
}
// 导出
export default { get, post, put, del, patch, cancelApi, cancelAllApi };