本文详细介绍如何使用 TypeScript 对 Axios 进行深度封装,构建一个类型安全、支持多级拦截器(类、实例、接口)及取消请求功能的 HTTP 客户端。通过自定义类型定义与泛型支持,确保开发过程中的代码提示与类型检查,提升项目维护效率与请求处理的灵活性。
前言
尽管 Fetch API 的使用率日益增高,但在部分老旧浏览器中仍缺乏支持。与此同时,axios 每周保持超过 2000 万次的下载量,这充分证明了其在当前技术栈中不可动摇的地位。接下来,我们将逐步进行封装,旨在实现一个既灵活又可复用的请求方法。
本次封装的 axios 模块需满足以下核心功能要求:
- 提供全面的代码类型提示;
- 支持灵活的拦截器机制;
- 支持创建多个实例,以便根据项目需求进行灵活调整;
- 每个实例或每个接口均可独立配置请求头、超时时间等参数;
- 支持取消请求功能,既可以根据 URL 取消单个特定请求,也能取消全部请求。
基础封装实现
首先,我们实现一个最基础的版本,具体实例代码如下:
// index.ts
import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
class Request {
// axios 实例
instance: AxiosInstance
constructor(config: AxiosRequestConfig) {
this.instance = axios.create(config)
}
request(config: AxiosRequestConfig) {
return this.instance.request(config)
}
}
export default Request
此处将其封装为一个类而非普通函数,主要因为类能够创建多个实例,从而拥有更广泛的适用范围和更强的封装性。
拦截器封装策略
接下来,我们对拦截器进行封装,该拦截器体系主要包含三种类型:
- 类级别拦截器
- 实例级别拦截器
- 接口级别拦截器
随后,我们将分别实现上述三种拦截器。
类级别拦截器
类级别拦截器的实现相对简单,只需在类中对 axios.create() 创建的实例调用 interceptors 下的两个拦截器方法即可,具体实例代码如下:
// index.ts
constructor(config: AxiosRequestConfig) {
this.instance = axios.create(config)
this.instance.interceptors.request.use(
(res: AxiosRequestConfig) => {
console.log('全局请求拦截器')
return res
},
(err: any) => err,
)
this.instance.interceptors.response.use(
// 因为我们接口的数据都在res.data下,所以我们直接返回res.data
(res: AxiosResponse) => {
console.log('全局响应拦截器')
return res.data
},
(err: any) => err,
)
}
在此处对响应拦截器进行简单处理,返回请求结果中的.data,因为接口数据主要存在于.data中,同data级的属性通常无需处理。
实例级别拦截器
实例级别拦截器的设计旨在保证封装的灵活性。由于不同实例在拦截后的处理逻辑可能各异,因此在定义实例时,允许传入特定的拦截器配置。
首先,我们定义相关的 interface 以提供类型提示,代码如下:
// types.ts
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
export interface RequestInterceptors {
// 请求拦截
requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig
requestInterceptorsCatch?: (err: any) => any
// 响应拦截
responseInterceptors?: (config: AxiosResponse) => AxiosResponse
responseInterceptorsCatch?: (err: any) => any
}
// 自定义传入的参数
export interface RequestConfig extends AxiosRequestConfig {
interceptors?: RequestInterceptors
}
在定义好基础拦截器后,我们需要改造传入参数的类型。由于 axios 提供的 AxiosRequestConfig 类型不允许直接传入自定义拦截器,因此我们自定义了 RequestConfig 类型,并使其继承自 AxiosRequestConfig 。
剩余部分的代码实现较为简单,如下所示:
// index.ts
import axios, { AxiosResponse } from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import type { RequestConfig, RequestInterceptors } from './types'
class Request {
// axios 实例
instance: AxiosInstance
// 拦截器对象
interceptorsObj?: RequestInterceptors
constructor(config: RequestConfig) {
this.instance = axios.create(config)
this.interceptorsObj = config.interceptors
this.instance.interceptors.request.use(
(res: AxiosRequestConfig) => {
console.log('全局请求拦截器')
return res
},
(err: any) => err,
)
// 使用实例拦截器
this.instance.interceptors.request.use(
this.interceptorsObj?.requestInterceptors,
this.interceptorsObj?.requestInterceptorsCatch,
)
this.instance.interceptors.response.use(
this.interceptorsObj?.responseInterceptors,
this.interceptorsObj?.responseInterceptorsCatch,
)
// 全局响应拦截器保证最后执行
this.instance.interceptors.response.use(
// 因为我们接口的数据都在res.data下,所以我们直接返回res.data
(res: AxiosResponse) => {
console.log('全局响应拦截器')
return res.data
},
(err: any) => err,
)
}
}
拦截器的执行顺序设定为:实例请求拦截 → 类请求拦截 → 实例响应拦截 → 类响应拦截。这种机制允许我们在实例层面实现差异化的拦截逻辑。
接口级别拦截器
现在,我们对单一接口进行拦截操作。首先,将 AxiosRequestConfig 类型修改为 RequestConfig,以允许传递拦截器配置;
随后,在类拦截器中将接口请求的数据进行返回。这意味着在 request() 方法中获取到的类型不再是 AxiosResponse 类型。
查阅 axios 的 index.d.ts 文件,可以看到对 request() 方法的类型定义如下:
// type.ts
request<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
这表明该方法允许传递类型参数,从而改变 request() 方法的返回值类型。我们的实现代码如下:
// index.ts
request<T>(config: RequestConfig): Promise<T> {
return new Promise((resolve, reject) => {
// 如果我们为单个请求设置拦截器,这里使用单个请求的拦截器
if (config.interceptors?.requestInterceptors) {
config = config.interceptors.requestInterceptors(config)
}
this.instance
.request<any, T>(config)
.then(res => {
// 如果我们为单个响应设置拦截器,这里使用单个响应的拦截器
if (config.interceptors?.responseInterceptors) {
res = config.interceptors.responseInterceptors<T>(res)
}
resolve(res)
})
.catch((err: any) => {
reject(err)
})
})
}
这里存在一个细节问题:拦截器接收的类型始终为 AxiosResponse 类型,而在类拦截器中返回类型已发生改变。因此,我们需要为拦截器传递一个泛型以适配这种变化,修改 types.ts 中的代码,示例如下:
// index.ts
export interface RequestInterceptors {
// 请求拦截
requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig
requestInterceptorsCatch?: (err: any) => any
// 响应拦截
responseInterceptors?: <T = AxiosResponse>(config: T) => T
responseInterceptorsCatch?: (err: any) => any
}
请求接口的拦截器最先执行,而响应拦截器最后执行。
封装请求方法
接下来,我们封装一个请求方法,首先是类的实例化过程,示例代码如下:
// index.ts
import Request from './request'
const request = new Request({
baseURL: import.meta.env.BASE_URL,
timeout: 1000 * 60 * 5,
interceptors: {
// 请求拦截器
requestInterceptors: config => {
console.log('实例请求拦截器')
return config
},
// 响应拦截器
responseInterceptors: result => {
console.log('实例响应拦截器')
return result
},
},
})
随后,我们封装一个用于发送网络请求的方法,代码如下:
// src/server/index.ts
import Request from './request'
import type { RequestConfig } from './request/types'
interface YWZRequestConfig<T> extends RequestConfig {
data?: T
}
interface YWZResponse<T> {
code: number
message: string
data: T
}
/**
* @description: 函数的描述
* @interface D 请求参数的interface
* @interface T 响应结构的intercept
* @param {YWZRequestConfig} config 不管是GET还是POST请求都使用data
* @returns {Promise}
*/
const ywzRequest = <D, T = any>(config: YWZRequestConfig<D>) => {
const { method = 'GET' } = config
if (method === 'get' || method === 'GET') {
config.params = config.data
}
return request.request<YWZResponse<T>>(config)
}
export default ywzRequest
该请求方式默认为 GET 方法,且一直使用 data 作为参数;
取消请求功能
应评论区 @Pic、@Michaelee 和 @Alone_Error 的建议,此处增加了取消请求功能。关于取消请求的具体概念,可参考官方文档说明。
准备工作
我们需要将所有请求的取消方法保存到一个集合中(此处使用数组,也可使用 Map),以便根据具体需求调用集合中的某个取消请求方法。
首先定义两个集合,示例代码如下:
// index.ts
import type {
RequestConfig,
RequestInterceptors,
CancelRequestSource,
} from './types'
class Request {
/*
存放取消方法的集合
* 在创建请求后将取消请求方法 push 到该集合中
* 封装一个方法,可以取消请求,传入 url: string|string[]
* 在请求之前判断同一URL是否存在,如果存在就取消请求
*/
cancelRequestSourceList?: CancelRequestSource[]
/*
存放所有请求URL的集合
* 请求之前需要将url push到该集合中
* 请求完毕后将url从集合中删除
* 添加在发送请求之前完成,删除在响应之后删除
*/
requestUrlList?: string[]
constructor(config: RequestConfig) {
// 数据初始化
this.requestUrlList = []
this.cancelRequestSourceList = []
}
}
此处使用了 CancelRequestSource 接口,我们需要对其进行定义:
// type.ts
export interface CancelRequestSource {
[index: string]: () => void
}
这里的 key 并非固定值,因为我们使用 url 作为 key,只有在实际使用时才能确定 url 的具体值,因此采用这种语法结构。
取消请求方法的添加与删除
首先,我们改造 request() 方法,它需要完成两项工作:一是在请求之前将 url 和取消请求方法 push 到我们前面定义的两个属性中;二是在请求完毕后(无论成功还是失败)将其删除。实现代码如下:
// index.ts
request<T>(config: RequestConfig): Promise<T> {
return new Promise((resolve, reject) => {
// 如果我们为单个请求设置拦截器,这里使用单个请求的拦截器
if (config.interceptors?.requestInterceptors) {
config = config.interceptors.requestInterceptors(config)
}
const url = config.url
// url存在保存取消请求方法和当前请求url
if (url) {
this.requestUrlList?.push(url)
config.cancelToken = new axios.CancelToken(c => {
this.cancelRequestSourceList?.push({
[url]: c,
})
})
}
this.instance
.request<any, T>(config)
.then(res => {
// 如果我们为单个响应设置拦截器,这里使用单个响应的拦截器
if (config.interceptors?.responseInterceptors) {
res = config.interceptors.responseInterceptors<T>(res)
}
resolve(res)
})
.catch((err: any) => {
reject(err)
})
.finally(() => {
url && this.delUrl(url)
})
})
}
此处将删除操作进行了抽离,封装为一个私有方法,示例代码如下:
// index.ts
/**
* @description: 获取指定 url 在 cancelRequestSourceList 中的索引
* @param {string} url
* @returns {number} 索引位置
*/
private getSourceIndex(url: string): number {
return this.cancelRequestSourceList?.findIndex(
(item: CancelRequestSource) => {
return Object.keys(item)[0] === url
},
) as number
}
/**
* @description: 删除 requestUrlList 和 cancelRequestSourceList
* @param {string} url
* @returns {*}
*/
private delUrl(url: string) {
const urlIndex = this.requestUrlList?.findIndex(u => u === url)
const sourceIndex = this.getSourceIndex(url)
// 删除url和cancel方法
urlIndex !== -1 && this.requestUrlList?.splice(urlIndex as number, 1)
sourceIndex !== -1 &&
this.cancelRequestSourceList?.splice(sourceIndex as number, 1)
}
取消请求方法实现
现在,我们可以封装取消请求和取消全部请求的功能。先来实现取消全部请求,这相对简单,只需调用 this.cancelRequestSourceList 中的所有方法即可,实现代码如下:
// index.ts
// 取消全部请求
cancelAllRequest() {
this.cancelRequestSourceList?.forEach(source => {
const key = Object.keys(source)[0]
source[key]()
})
}
接下来封装取消单个请求的方法,因为它可以取消一个或多个请求,其参数为 url 或包含多个 URL 的数组。根据传值的不同执行相应的操作,实现代码如下:
// index.ts
// 取消请求
cancelRequest(url: string | string[]) {
if (typeof url === 'string') {
// 取消单个请求
const sourceIndex = this.getSourceIndex(url)
sourceIndex >= 0 && this.cancelRequestSourceList?.[sourceIndex][url]()
} else {
// 存在多个需要取消请求的地址
url.forEach(u => {
const sourceIndex = this.getSourceIndex(u)
sourceIndex >= 0 && this.cancelRequestSourceList?.[sourceIndex][u]()
})
}
}
测试环节
测试请求方法
现在我们来测试上述请求方法。此处使用 www.apishop.net/ 提供的免费 API 进行测试,测试代码如下:
<script setup lang="ts">
// app.vue
import request from './service'
import { onMounted } from 'vue'
interface Req {
apiKey: string
area?: string
areaID?: string
}
interface Res {
area: string
areaCode: string
areaid: string
dayList: any[]
}
const get15DaysWeatherByArea = (data: Req) => {
return request<Req, Res>({
url: '/api/common/weather/get15DaysWeatherByArea',
method: 'GET',
data,
interceptors: {
requestInterceptors(res) {
console.log('接口请求拦截')
return res
},
responseInterceptors(result) {
console.log('接口响应拦截')
return result
},
},
})
}
onMounted(async () => {
const res = await get15DaysWeatherByArea({
apiKey: import.meta.env.VITE_APP_KEY,
area: '北京市',
})
console.log(res.result.dayList)
})
</script>
如果在实际开发中,建议将这些代码分别抽离至不同模块。
上述代码在命令行中的输出结果为:
接口请求拦截 实例请求拦截器 全局请求拦截器 实例响应拦截器 全局响应拦截器 接口响应拦截 [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
测试取消请求
首先,我们在 .server/index.ts 中对取消请求方法进行导出,实现代码如下:
// 取消请求
export const cancelRequest = (url: string | string[]) => {
return request.cancelRequest(url)
}
// 取消全部请求
export const cancelAllRequest = () => {
return request.cancelAllRequest()
}
然后,我们在 app.vue 中对其进行引用,实现代码如下:
<template>
<el-button
@click="cancelRequest('/api/common/weather/get15DaysWeatherByArea')"
>取消请求</el-button
>
<el-button @click="cancelAllRequest">取消全部请求</el-button>
<router-view></router-view>
</template>
<script setup lang="ts">
import request, { cancelRequest, cancelAllRequest } from './service'
</script>
发送请求后,点击按钮即可实现对应的取消功能。
总结
本文到此结束。如果文章对您有所帮助,欢迎点赞支持;若文中存在错误或您有更好的见解,欢迎指正交流。
项目地址:ywanzhou/vue3-template (github.com)
以上就是关于项目中使用 Typescript 封装 axios 的详细内容,更多有关 Typescript 封装 axios 的资料请关注本站其他相关文章!