TypeScript 封装 Axios 实战:类型定义与拦截器配置

作者:闭包旅人时间:2026-10-26 02:59:58浏览:498

本文基于 TypeScript 深入解析 Axios 的核心类型,包括 AxiosRequestConfig、AxiosInstance、AxiosResponse 及 AxiosError。通过实战代码演示如何封装 Axios 实例,配置请求与响应拦截器以处理 Token 和全局错误,并利用泛型机制实现接口返回数据的类型提示,提升前端开发效率与代码健壮性。

简介

这是TypeScript实战系列的第三篇。前两篇文章分别探讨了在 Vuex 和 Pinia 中使用TypeScript的方法,并对比了Vuex与Pinia的差异。本文将继续使用TypeScript对Axios进行封装,旨在进一步巩固TypeScript的基础应用。

Axios几个常用类型

在利用TypeScript封装Axios之前,首先需要了解Axios中几个关键的数据类型定义。

AxiosRequestConfig

AxiosRequestConfig是调用axios发送请求时传递配置参数的类型,同时也是请求拦截器中接收的参数类型。

axios(config: AxiosRequestConfig)

该config包含较多参数,日常开发中常用的有url、method、params、data、headers、baseURL、timeout。

export interface AxiosRequestConfig {
  url?: string;
  method?: Method;
  baseURL?: string;
  transformRequest?: AxiosTransformer | AxiosTransformer[];
  transformResponse?: AxiosTransformer | AxiosTransformer[];
  headers?: any;
  params?: any;
  paramsSerializer?: (params: any) => string;
  data?: any;
  timeout?: number;
  timeoutErrorMessage?: string;
  withCredentials?: boolean;
  adapter?: AxiosAdapter;
  auth?: AxiosBasicCredentials;
  responseType?: ResponseType;
  xsrfCookieName?: string;
  xsrfHeaderName?: string;
  onUploadProgress?: (progressEvent: any) => void;
  onDownloadProgress?: (progressEvent: any) => void;
  maxContentLength?: number;
  validateStatus?: ((status: number) => boolean) | null;
  maxBodyLength?: number;
  maxRedirects?: number;
  socketPath?: string | null;
  httpAgent?: any;
  httpsAgent?: any;
  proxy?: AxiosProxyConfig | false;
  cancelToken?: CancelToken;
  decompress?: boolean;
  transitional?: TransitionalOptions
}

AxiosInstance

AxiosInstance代表通过axios创建的实例对象类型。

通过axios.create(config?: AxiosRequestConfig)方法创建出的对象均属于AxiosInstance类型。

export interface AxiosInstance {
  (config: AxiosRequestConfig): AxiosPromise;
  (url: string, config?: AxiosRequestConfig): AxiosPromise;
  defaults: AxiosRequestConfig;
  interceptors: {
    request: AxiosInterceptorManager<AxiosRequestConfig>;
    response: AxiosInterceptorManager<AxiosResponse>;
  };
  getUri(config?: AxiosRequestConfig): string;
  request<T = any, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R>;
  get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
  delete<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
  head<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
  options<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
  post<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
  put<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
  patch<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
}

虽然可以使用axios.create、axios.all、axios.spread等方法,但AxiosInstance类型本身并未直接包含create、all、spread等方法,因此需要探究axios的实际类型结构。

AxiosStatic

export interface AxiosStatic extends AxiosInstance {
  create(config?: AxiosRequestConfig): AxiosInstance;
  Cancel: CancelStatic;
  CancelToken: CancelTokenStatic;
  isCancel(value: any): boolean;
  all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
  spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
  isAxiosError(payload: any): payload is AxiosError;
}
declare const axios: AxiosStatic;

实际上,axios属于AxiosStatic类型,并继承了AxiosInstance类型,它是两者的结合体。相比axios.create(config?: AxiosRequestConfig)创建的实例对象,axios提供了更强大的功能。

AxiosResponse

AxiosResponse至关重要,axios请求的返回值类型均为AxiosResponse。其中AxiosResponse是一个接口泛型,该泛型会作用于后端返回的data数据。因此,我们可以根据后端接口规范定义不同的类型传入,后续在封装常用方法时将详细展开。

export interface AxiosResponse<T = any>  {
  data: T;
  status: number;
  statusText: string;
  headers: any;
  config: AxiosRequestConfig;
  request?: any;
}

AxiosError

AxiosError是必须掌握的类型,响应拦截器中捕获的错误对象即为AxiosError类型。

export interface AxiosError<T = any> extends Error {
  config: AxiosRequestConfig;
  code?: string;
  request?: any;
  response?: AxiosResponse<T>;
  isAxiosError: boolean;
  toJSON: () => object;
}

了解了Axios的常用类型后,接下来正式使用TS来封装Axios。

基础封装

首先实现一个最基础的版本,示例代码如下:

// index.ts
import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

class Request {
  // axios 实例
  instance: AxiosInstance
  // 基础配置,url和超时时间
  baseConfig: AxiosRequestConfig = {baseURL: "/api", timeout: 60000}

  constructor(config: AxiosRequestConfig) {
    // 使用axios.create创建axios实例
    this.instance = axios.create(Object.assign(this.baseConfig, config))
  }
  // 定义请求方法
  public request(config: AxiosRequestConfig): Promise<AxiosResponse> {
    return this.instance.request(config)
  }
}
export default Request

在实际项目中,仅有基础请求方法是不够的,还需要进一步封装拦截器和常用方法。

拦截器封装

拦截器的封装只需在类中调用由axios.create()创建的实例的interceptors下的两个拦截器方法即可。

具体实现代码如下:

// index.ts
constructor(config: AxiosRequestConfig) {
  this.instance = axios.create(Object.assign(this.baseConfig, config))
  this.instance.interceptors.request.use(
    (config: AxiosRequestConfig) => {
      // 一般会请求拦截里面加token
      const token = localStorage.getItem("token")
      config.headers["Authorization"] = token;
      
      return config
    },
    (err: any) => {
      return Promise.reject(err)
    },
  )
  this.instance.interceptors.response.use(
    (res: AxiosResponse) => {
      // 直接返回res,当然你也可以只返回res.data
      return res
    },
    (err: any) => {
      // 这里用来处理http常见错误,进行全局提示
      let message = "";
      switch (err.response.status) {
        case 400:
          message = "请求错误(400)";
          break;
        case 401:
          message = "未授权,请重新登录(401)";
          // 这里可以做清空storage并跳转到登录页的操作
          break;
        case 403:
          message = "拒绝访问(403)";
          break;
        case 404:
          message = "请求出错(404)";
          break;
        case 408:
          message = "请求超时(408)";
          break;
        case 500:
          message = "服务器错误(500)";
          break;
        case 501:
          message = "服务未实现(501)";
          break;
        case 502:
          message = "网络错误(502)";
          break;
        case 503:
          message = "服务不可用(503)";
          break;
        case 504:
          message = "网络超时(504)";
          break;
        case 505:
          message = "HTTP版本不受支持(505)";
          break;
        default:
          message = `连接出错(${err.response.status})!`;
      }
      // 这里错误消息可以使用全局弹框展示出来
      // 比如element plus 可以使用 ElMessage
      ElMessage({
        showClose: true,
        message: `${message},请检查网络或联系管理员!`,
        type: "error",
      });
      // 这里是AxiosError类型,所以一般我们只reject我们需要的响应即可
      return Promise.reject(err.response)
    },
  )
}

此处分别处理了请求拦截器和响应拦截器。在请求拦截器中,我们为请求头添加了token。

在响应拦截器中,返回了完整的response对象;当然,也可以仅返回后端返回的response.data,具体可根据个人偏好调整。此外,还对http错误进行了全局统一处理。

常用方法封装

在基础封装中,我们定义了一个request通用方法。实际上,还可以进一步封装get、post、put、delete等方法,以提升使用便捷性。

前文分析指出,AxiosResponse是一个泛型接口,可接受一个泛型参数并作用于data字段。因此,我们可以在此处定义后端通用的返回数据结构类型。

例如,若某项目后端接口无论成功或失败,返回结构始终包含code、message、results,则可定义如下数据类型。

type Result<T> = {
  code: number,
  message: string,
  result: T
}

将该类型传递给各个方法:

public get<T = any>(
  url: string, 
  config?: AxiosRequestConfig
): Promise<AxiosResponse<Result<T>>> {
  return this.instance.get(url, config);
}
public post<T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<AxiosResponse<Result<T>>> {
  return this.instance.post(url, data, config);
}
public put<T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<AxiosResponse<Result<T>>> {
  return this.instance.put(url, data, config);
}
public delete<T = any>(
  url: string,
  config?: AxiosRequestConfig
): Promise<AxiosResponse<Result<T>>> {
  return this.instance.delete(url, config);
}

这样在调用接口时,即可看到返回的data具有我们定义的Result类型。

简介

由此可获得自动类型提示:

简介

上述调用接口时未传递接口数据类型,导致result为any类型。若希望每个接口都有明确的类型提示,需向方法传递泛型。

进一步优化,定义一个login接口返回值类型loginType。

type loginType = {
  token: string;
};

在调用方法时传入该类型,再观察返回值data的类型。

简介

结果显示其为Result<loginType>类型,其中loginType即为result的类型。

因此,我们的result可进一步获得更精确的类型提示。

简介

虽然为每个接口定义返回值类型效果良好,但会显著增加前端工作量。在编写请求方法时,若不传递接口返回值类型,result的类型将默认为any。开发者可根据项目实际需求选择使用方式。

至此,是否已完全理解?如有任何疑问,欢迎留言讨论。

总结

经过上述讲解,部分读者可能感到复杂,下面对axios的封装过程进行总结。

// index.ts
import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
type Result<T> = {
  code: number;
  message: string;
  result: T;
};
class Request {
  // axios 实例
  instance: AxiosInstance;
  // 基础配置,url和超时时间
  baseConfig: AxiosRequestConfig = { baseURL: "/api", timeout: 60000 };

  constructor(config: AxiosRequestConfig) {
    // 使用axios.create创建axios实例
    this.instance = axios.create(Object.assign(this.baseConfig, config));

    this.instance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        // 一般会请求拦截里面加token
        const token = localStorage.getItem("token");
        config.headers["Authorization"] = token;

        return config;
      },
      (err: any) => {
        return Promise.reject(err);
      }
    );

    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        // 直接返回res,当然你也可以只返回res.data
        return res;
      },
      (err: any) => {
        // 这里用来处理http常见错误,进行全局提示
        let message = "";
        switch (err.response.status) {
          case 400:
            message = "请求错误(400)";
            break;
          case 401:
            message = "未授权,请重新登录(401)";
            // 这里可以做清空storage并跳转到登录页的操作
            break;
          case 403:
            message = "拒绝访问(403)";
            break;
          case 404:
            message = "请求出错(404)";
            break;
          case 408:
            message = "请求超时(408)";
            break;
          case 500:
            message = "服务器错误(500)";
            break;
          case 501:
            message = "服务未实现(501)";
            break;
          case 502:
            message = "网络错误(502)";
            break;
          case 503:
            message = "服务不可用(503)";
            break;
          case 504:
            message = "网络超时(504)";
            break;
          case 505:
            message = "HTTP版本不受支持(505)";
            break;
          default:
            message = `连接出错(${err.response.status})!`;
        }
        // 这里错误消息可以使用全局弹框展示出来
        // 比如element plus 可以使用 ElMessage
        ElMessage({
          showClose: true,
          message: `${message},请检查网络或联系管理员!`,
          type: "error",
        });
        // 这里是AxiosError类型,所以一般我们只reject我们需要的响应即可
        return Promise.reject(err.response);
      }
    );
  }

  // 定义请求方法
  public request(config: AxiosRequestConfig): Promise<AxiosResponse> {
    return this.instance.request(config);
  }

  public get<T = any>(
    url: string,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse<Result<T>>> {
    return this.instance.get(url, config);
  }
  public post<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse<Result<T>>> {
    return this.instance.post(url, data, config);
  }
  public put<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse<Result<T>>> {
    return this.instance.put(url, data, config);
  }

  public delete<T = any>(
    url: string,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse<Result<T>>> {
    return this.instance.delete(url, config);
  }
}
export default Request;

本文关于TypeScript利用TS封装Axios的实战内容到此结束,更多相关TypeScript封装Axios内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

作者最新文章
相关文章
更多