項(xiàng)目中使用Typescript封裝axios
寫在前面
雖然說Fetch API已經(jīng)使用率已經(jīng)非常的高了,但是在一些老的瀏覽器還是不支持的,而且axios仍然每周都保持2000多萬的下載量,這就說明了axios仍然存在不可撼動(dòng)的地位,接下來我們就一步一步的去封裝,實(shí)現(xiàn)一個(gè)靈活、可復(fù)用的一個(gè)請(qǐng)求請(qǐng)發(fā)。
這篇文章封裝的axios已經(jīng)滿足如下功能:
- 無處不在的代碼提示;
- 靈活的攔截器;
- 可以創(chuàng)建多個(gè)實(shí)例,靈活根據(jù)項(xiàng)目進(jìn)行調(diào)整;
- 每個(gè)實(shí)例,或者說每個(gè)接口都可以靈活配置請(qǐng)求頭、超時(shí)時(shí)間等;
- 取消請(qǐng)求(可以根據(jù)url取消單個(gè)請(qǐng)求也可以取消全部請(qǐng)求)。
基礎(chǔ)封裝
首先我們實(shí)現(xiàn)一個(gè)最基本的版本,實(shí)例代碼如下:
// index.ts
import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
class Request {
// axios 實(shí)例
instance: AxiosInstance
constructor(config: AxiosRequestConfig) {
this.instance = axios.create(config)
}
request(config: AxiosRequestConfig) {
return this.instance.request(config)
}
}
export default Request
這里將其封裝為一個(gè)類,而不是一個(gè)函數(shù)的原因是因?yàn)轭惪梢詣?chuàng)建多個(gè)實(shí)例,適用范圍更廣,封裝性更強(qiáng)一些。
攔截器封裝
首先我們封裝一下攔截器,這個(gè)攔截器分為三種:
- 類攔截器
- 實(shí)例攔截器
- 接口攔截器
接下來我們就分別實(shí)現(xiàn)這三個(gè)攔截器。
類攔截器
類攔截器比較容易實(shí)現(xiàn),只需要在類中對(duì)axios.create()創(chuàng)建的實(shí)例調(diào)用interceptors下的兩個(gè)攔截器即可,實(shí)例代碼如下:
// index.ts
constructor(config: AxiosRequestConfig) {
this.instance = axios.create(config)
this.instance.interceptors.request.use(
(res: AxiosRequestConfig) => {
console.log('全局請(qǐng)求攔截器')
return res
},
(err: any) => err,
)
this.instance.interceptors.response.use(
// 因?yàn)槲覀兘涌诘臄?shù)據(jù)都在res.data下,所以我們直接返回res.data
(res: AxiosResponse) => {
console.log('全局響應(yīng)攔截器')
return res.data
},
(err: any) => err,
)
}
我們?cè)谶@里對(duì)響應(yīng)攔截器做了一個(gè)簡單的處理,就是將請(qǐng)求結(jié)果中的.data進(jìn)行返回,因?yàn)槲覀儗?duì)接口請(qǐng)求的數(shù)據(jù)主要是存在在.data中,跟data同級(jí)的屬性我們基本是不需要的。
實(shí)例攔截器
實(shí)例攔截器是為了保證封裝的靈活性,因?yàn)槊恳粋€(gè)實(shí)例中的攔截后處理的操作可能是不一樣的,所以在定義實(shí)例時(shí),允許我們傳入攔截器。
首先我們定義一下interface,方便類型提示,代碼如下:
// types.ts
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
export interface RequestInterceptors {
// 請(qǐng)求攔截
requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig
requestInterceptorsCatch?: (err: any) => any
// 響應(yīng)攔截
responseInterceptors?: (config: AxiosResponse) => AxiosResponse
responseInterceptorsCatch?: (err: any) => any
}
// 自定義傳入的參數(shù)
export interface RequestConfig extends AxiosRequestConfig {
interceptors?: RequestInterceptors
}
定義好基礎(chǔ)的攔截器后,我們需要改造我們傳入的參數(shù)的類型,因?yàn)閍xios提供的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 實(shí)例
instance: AxiosInstance
// 攔截器對(duì)象
interceptorsObj?: RequestInterceptors
constructor(config: RequestConfig) {
this.instance = axios.create(config)
this.interceptorsObj = config.interceptors
this.instance.interceptors.request.use(
(res: AxiosRequestConfig) => {
console.log('全局請(qǐng)求攔截器')
return res
},
(err: any) => err,
)
// 使用實(shí)例攔截器
this.instance.interceptors.request.use(
this.interceptorsObj?.requestInterceptors,
this.interceptorsObj?.requestInterceptorsCatch,
)
this.instance.interceptors.response.use(
this.interceptorsObj?.responseInterceptors,
this.interceptorsObj?.responseInterceptorsCatch,
)
// 全局響應(yīng)攔截器保證最后執(zhí)行
this.instance.interceptors.response.use(
// 因?yàn)槲覀兘涌诘臄?shù)據(jù)都在res.data下,所以我們直接返回res.data
(res: AxiosResponse) => {
console.log('全局響應(yīng)攔截器')
return res.data
},
(err: any) => err,
)
}
}
我們的攔截器的執(zhí)行順序?yàn)閷?shí)例請(qǐng)求→類請(qǐng)求→實(shí)例響應(yīng)→類響應(yīng);這樣我們就可以在實(shí)例攔截上做出一些不同的攔截,
接口攔截
現(xiàn)在我們對(duì)單一接口進(jìn)行攔截操作,首先我們將AxiosRequestConfig類型修改為RequestConfig允許傳遞攔截器;
然后我們?cè)陬悢r截器中將接口請(qǐng)求的數(shù)據(jù)進(jìn)行了返回,也就是說在request()方法中得到的類型就不是AxiosResponse類型了。
我們查看axios的index.d.ts中,對(duì)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) => {
// 如果我們?yōu)閱蝹€(gè)請(qǐng)求設(shè)置攔截器,這里使用單個(gè)請(qǐng)求的攔截器
if (config.interceptors?.requestInterceptors) {
config = config.interceptors.requestInterceptors(config)
}
this.instance
.request<any, T>(config)
.then(res => {
// 如果我們?yōu)閱蝹€(gè)響應(yīng)設(shè)置攔截器,這里使用單個(gè)響應(yīng)的攔截器
if (config.interceptors?.responseInterceptors) {
res = config.interceptors.responseInterceptors<T>(res)
}
resolve(res)
})
.catch((err: any) => {
reject(err)
})
})
}
這里還存在一個(gè)細(xì)節(jié),就是我們?cè)跀r截器接受的類型一直是AxiosResponse類型,而在類攔截器中已經(jīng)將返回的類型改變,所以說我們需要為攔截器傳遞一個(gè)泛型,從而使用這種變化,修改types.ts中的代碼,示例如下:
// index.ts
export interface RequestInterceptors {
// 請(qǐng)求攔截
requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig
requestInterceptorsCatch?: (err: any) => any
// 響應(yīng)攔截
responseInterceptors?: <T = AxiosResponse>(config: T) => T
responseInterceptorsCatch?: (err: any) => any
}
請(qǐng)求接口攔截是最前執(zhí)行,而響應(yīng)攔截是最后執(zhí)行。
封裝請(qǐng)求方法
現(xiàn)在我們就來封裝一個(gè)請(qǐng)求方法,首先是類進(jìn)行實(shí)例化示例代碼如下:
// index.ts
import Request from './request'
const request = new Request({
baseURL: import.meta.env.BASE_URL,
timeout: 1000 * 60 * 5,
interceptors: {
// 請(qǐng)求攔截器
requestInterceptors: config => {
console.log('實(shí)例請(qǐng)求攔截器')
return config
},
// 響應(yīng)攔截器
responseInterceptors: result => {
console.log('實(shí)例響應(yīng)攔截器')
return result
},
},
})
然后我們封裝一個(gè)請(qǐng)求方法, 來發(fā)送網(wǎng)絡(luò)請(qǐng)求,代碼如下:
// 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: 函數(shù)的描述
* @interface D 請(qǐng)求參數(shù)的interface
* @interface T 響應(yīng)結(jié)構(gòu)的intercept
* @param {YWZRequestConfig} config 不管是GET還是POST請(qǐng)求都使用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
該請(qǐng)求方式默認(rèn)為GET,且一直用data作為參數(shù);
取消請(qǐng)求
應(yīng)評(píng)論區(qū)@Pic、@Michaelee和@Alone_Error的建議,這里增加了一個(gè)取消請(qǐng)求;關(guān)于什么是取消請(qǐng)求可以參考官方文檔。
準(zhǔn)備工作
我們需要將所有請(qǐng)求的取消方法保存到一個(gè)集合(這里我用的數(shù)組,也可以使用Map)中,然后根據(jù)具體需要去調(diào)用這個(gè)集合中的某個(gè)取消請(qǐng)求方法。
首先定義兩個(gè)集合,示例代碼如下:
// index.ts
import type {
RequestConfig,
RequestInterceptors,
CancelRequestSource,
} from './types'
class Request {
/*
存放取消方法的集合
* 在創(chuàng)建請(qǐng)求后將取消請(qǐng)求方法 push 到該集合中
* 封裝一個(gè)方法,可以取消請(qǐng)求,傳入 url: string|string[]
* 在請(qǐng)求之前判斷同一URL是否存在,如果存在就取消請(qǐng)求
*/
cancelRequestSourceList?: CancelRequestSource[]
/*
存放所有請(qǐng)求URL的集合
* 請(qǐng)求之前需要將url push到該集合中
* 請(qǐng)求完畢后將url從集合中刪除
* 添加在發(fā)送請(qǐng)求之前完成,刪除在響應(yīng)之后刪除
*/
requestUrlList?: string[]
constructor(config: RequestConfig) {
// 數(shù)據(jù)初始化
this.requestUrlList = []
this.cancelRequestSourceList = []
}
}
這里用的CancelRequestSource接口,我們?nèi)ザx一下:
// type.ts
export interface CancelRequestSource {
[index: string]: () => void
}
這里的key是不固定的,因?yàn)槲覀兪褂?code>url做key,只有在使用的時(shí)候才知道url,所以這里使用這種語法。
取消請(qǐng)求方法的添加與刪除
首先我們改造一下request()方法,它需要完成兩個(gè)工作,一個(gè)就是在請(qǐng)求之前將url和取消請(qǐng)求方法push到我們前面定義的兩個(gè)屬性中,然后在請(qǐng)求完畢后(不管是失敗還是成功)都將其進(jìn)行刪除,實(shí)現(xiàn)代碼如下:
// index.ts
request<T>(config: RequestConfig): Promise<T> {
return new Promise((resolve, reject) => {
// 如果我們?yōu)閱蝹€(gè)請(qǐng)求設(shè)置攔截器,這里使用單個(gè)請(qǐng)求的攔截器
if (config.interceptors?.requestInterceptors) {
config = config.interceptors.requestInterceptors(config)
}
const url = config.url
// url存在保存取消請(qǐng)求方法和當(dāng)前請(qǐng)求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 => {
// 如果我們?yōu)閱蝹€(gè)響應(yīng)設(shè)置攔截器,這里使用單個(gè)響應(yīng)的攔截器
if (config.interceptors?.responseInterceptors) {
res = config.interceptors.responseInterceptors<T>(res)
}
resolve(res)
})
.catch((err: any) => {
reject(err)
})
.finally(() => {
url && this.delUrl(url)
})
})
}
這里我們將刪除操作進(jìn)行了抽離,將其封裝為一個(gè)私有方法,示例代碼如下:
// 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)
}
取消請(qǐng)求方法
現(xiàn)在我們就可以封裝取消請(qǐng)求和取消全部請(qǐng)求了,我們先來封裝一下取消全部請(qǐng)求吧,這個(gè)比較簡單,只需要調(diào)用this.cancelRequestSourceList中的所有方法即可,實(shí)現(xiàn)代碼如下:
// index.ts
// 取消全部請(qǐng)求
cancelAllRequest() {
this.cancelRequestSourceList?.forEach(source => {
const key = Object.keys(source)[0]
source[key]()
})
}
現(xiàn)在我們封裝一下取消請(qǐng)求,因?yàn)樗梢匀∠粋€(gè)和多個(gè),那它的參數(shù)就是url,或者包含多個(gè)URL的數(shù)組,然后根據(jù)傳值的不同去執(zhí)行不同的操作,實(shí)現(xiàn)代碼如下:
// index.ts
// 取消請(qǐng)求
cancelRequest(url: string | string[]) {
if (typeof url === 'string') {
// 取消單個(gè)請(qǐng)求
const sourceIndex = this.getSourceIndex(url)
sourceIndex >= 0 && this.cancelRequestSourceList?.[sourceIndex][url]()
} else {
// 存在多個(gè)需要取消請(qǐng)求的地址
url.forEach(u => {
const sourceIndex = this.getSourceIndex(u)
sourceIndex >= 0 && this.cancelRequestSourceList?.[sourceIndex][u]()
})
}
}
測試
測試請(qǐng)求方法
現(xiàn)在我們就來測試一下這個(gè)請(qǐng)求方法,這里我們使用www.apishop.net/提供的免費(fèi)API進(jìn)行測試,測試代碼如下:
<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('接口請(qǐng)求攔截')
return res
},
responseInterceptors(result) {
console.log('接口響應(yīng)攔截')
return result
},
},
})
}
onMounted(async () => {
const res = await get15DaysWeatherByArea({
apiKey: import.meta.env.VITE_APP_KEY,
area: '北京市',
})
console.log(res.result.dayList)
})
</script>
如果在實(shí)際開發(fā)中可以將這些代碼分別抽離。
上面的代碼在命令中輸出
接口請(qǐng)求攔截
實(shí)例請(qǐng)求攔截器
全局請(qǐng)求攔截器
實(shí)例響應(yīng)攔截器
全局響應(yīng)攔截器
接口響應(yīng)攔截
[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
測試取消請(qǐng)求
首先我們?cè)?code>.server/index.ts中對(duì)取消請(qǐng)求方法進(jìn)行導(dǎo)出,實(shí)現(xiàn)代碼如下:
// 取消請(qǐng)求
export const cancelRequest = (url: string | string[]) => {
return request.cancelRequest(url)
}
// 取消全部請(qǐng)求
export const cancelAllRequest = () => {
return request.cancelAllRequest()
}
然后我們?cè)?code>app.vue中對(duì)其進(jìn)行引用,實(shí)現(xiàn)代碼如下:
<template>
<el-button
@click="cancelRequest('/api/common/weather/get15DaysWeatherByArea')"
>取消請(qǐng)求</el-button
>
<el-button @click="cancelAllRequest">取消全部請(qǐng)求</el-button>
<router-view></router-view>
</template>
<script setup lang="ts">
import request, { cancelRequest, cancelAllRequest } from './service'
</script>
發(fā)送請(qǐng)求后,點(diǎn)擊按鈕即可實(shí)現(xiàn)對(duì)應(yīng)的功能
寫在最后
本篇文章到這里就結(jié)束了,如果文章對(duì)你有用,可以三連支持一下,如果文章中有錯(cuò)誤或者說你有更好的見解,歡迎指正~
項(xiàng)目地址:ywanzhou/vue3-template (github.com)
以上就是項(xiàng)目中使用Typescript封裝axios的詳細(xì)內(nèi)容,更多關(guān)于Typescript封裝axios的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
js鼠標(biāo)按鍵事件和鍵盤按鍵事件用法實(shí)例匯總
這篇文章主要介紹了js鼠標(biāo)按鍵事件和鍵盤按鍵事件用法,結(jié)合實(shí)例形式總結(jié)分析了JavaScript針對(duì)鼠標(biāo)與鍵盤事件的常用操作技巧,需要的朋友可以參考下2016-10-10
3種js實(shí)現(xiàn)string的substring方法
這篇文章主要介紹了3種javascript實(shí)現(xiàn)string的substring方法,需要的朋友可以參考下2015-11-11
微信小程序?qū)崿F(xiàn)點(diǎn)餐小程序左側(cè)滑動(dòng)菜單
這篇文章主要為大家詳細(xì)介紹了微信小程序?qū)崿F(xiàn)點(diǎn)餐小程序左側(cè)滑動(dòng)菜單,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-07-07
JS使用window.requestAnimationFrame()對(duì)列表切片進(jìn)行渲染
這篇文章主要為大家介紹了JS使用requestAnimationFrame對(duì)列表切片進(jìn)行渲染,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05
javascript實(shí)現(xiàn)簡易的計(jì)算器
這篇文章主要為大家詳細(xì)介紹了javascript實(shí)現(xiàn)簡易的計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-01-01
使用JavaScript實(shí)現(xiàn)簡單圖像放大鏡效果
圖像放大鏡在很多網(wǎng)站中都扮演著重要的角色,大多數(shù)開發(fā)人員使用?jquery?來創(chuàng)建圖像放大鏡。在本教程中,我將向大家展示如何使用?HTML、CSS?和?JavaScript?制作一個(gè)簡單的圖像放大鏡,需要的可以參考一下2022-08-08
JavaScript下通過的XMLHttpRequest發(fā)送請(qǐng)求的代碼
JavaScript下通過的XMLHttpRequest發(fā)送請(qǐng)求的代碼,需要的朋友可以參考下。2011-06-06

