• 使用 Typescript 封装 Axios


    对 axios 二次封装,更加的可配置化、扩展性更加强大灵活

    通过 class 类实现,class 具备更强封装性(封装、继承、多态),通过实例化类传入自定义的配置

    创建 class

    严格要求实例化时传入的配置,拥有更好的代码提示

    /**
     * @param {AxiosInstance} axios实例类型
     * @param {AxiosRequestConfig} axios配置项类型
     */
    import type { AxiosInstance, AxiosRequestConfig } from 'axios'
    ​
    class Http {
        axios: AxiosInstance
        constructor(config: AxiosRequestConfig) {
            // 创建一个实例 axios.create([config])
            this.axios = axios.create(config)
      }
    }
    ​
    // 每实例化一个 axios 时,都是不同的 axios 示例,互不干扰
    new Http({
        baseURL:'qq.com';
        timeout:60 * 1
    });
    ​
    new Http({
        baseURL:'web.com'
    }); 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    axios.create([config])
    const instance = axios.create({
    baseURL: 'https://some-domain.com/api/',
    timeout: 1000,
    headers: {'X-Custom-Header': 'foobar'}
    }); 
    
    • 1
    • 2
    • 3
    • 4
    • 5

    AxiosRequestConfig 的类型注解

    export interface AxiosRequestConfig {
      url?: string;
      method?: Method | string;
      baseURL?: string;
      transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
      transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
      headers?: AxiosRequestHeaders;
      params?: any;
      paramsSerializer?: (params: any) => string;
      data?: D;
      timeout?: number;
      timeoutErrorMessage?: string;
      withCredentials?: boolean;
      adapter?: AxiosAdapter;
      auth?: AxiosBasicCredentials;
      responseType?: ResponseType;
      responseEncoding?: responseEncoding | string;
      xsrfCookieName?: string;
      xsrfHeaderName?: string;
      onUploadProgress?: (progressEvent: any) => void;
      onDownloadProgress?: (progressEvent: any) => void;
      maxContentLength?: number;
      validateStatus?: ((status: number) => boolean) | null;
      maxBodyLength?: number;
      maxRedirects?: number;
      beforeRedirect?: (options: Record, responseDetails: {headers: Record}) => void;
      socketPath?: string | null;
      httpAgent?: any;
      httpsAgent?: any;
      proxy?: AxiosProxyConfig | false;
      cancelToken?: CancelToken;
      decompress?: boolean;
      transitional?: TransitionalOptions;
      signal?: AbortSignal;
      insecureHTTPParser?: boolean;
      env?: {
        FormData?: new (...args: any[]) => object;};
    } 
    
    • 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

    封装 request(config)通用方法

    /**
    * axios#request(config)
    * @param {*} config
    * @returns {*}
    */
    request(config: AxiosRequestConfig) {
        return this.axios.request(config)
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    🏹 在 axios 中,request中的 config 参数与实例化时,axios.create(config)传入的参数是相同的,以下是 axios 方法具体参数

    axios.request(config)
    axios.get(url[, config])
    axios.delete(url[, config])
    axios.head(url[, config])
    axios.options(url[, config])
    axios.post(url[, data[, config]])
    axios.put(url[, data[, config]])
    axios.patch(url[, data[, config]])
    axios.getUri([config]) 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    封装-拦截器(单个实例独享)

    拦截器的hooks,在请求或响应被 then 或 catch 处理前拦截处理

    🛹在请求中,如携带token、loading动画、header配置...,都是一些公有的逻辑ÿ

  • 相关阅读:
    国内算力真的紧缺么?
    每天五分钟机器学习:数据和特征决定机器学习的上限(特征工程)
    GBASE 8s的数据导入和导出
    基于Java+vue前后端分离大学学术交流论坛设计实现(源码+lw+部署文档+讲解等)
    迅速了解JDK线程池以及Spring线程池
    企业AI虚拟ip形象定制的应用场景
    java springboot VUE粮食经销系统开发mysql数据库web结构java编程计算机网页源码maven项目
    开发语言漫谈-Vue
    LeetCode 热题 HOT 100 第八十天 494. 目标和 中等题 用python3求解
    【网络原理】基本原理篇:I/O
  • 原文地址:https://blog.csdn.net/web2022050903/article/details/127902507