新聞中心
這篇文章封裝的axios已經(jīng)滿足如下功能:

成都創(chuàng)新互聯(lián)是一家業(yè)務(wù)范圍包括IDC托管業(yè)務(wù),虛擬空間、主機(jī)租用、主機(jī)托管,四川、重慶、廣東電信服務(wù)器租用,重慶服務(wù)器托管,成都網(wǎng)通服務(wù)器托管,成都服務(wù)器租用,業(yè)務(wù)范圍遍及中國(guó)大陸、港澳臺(tái)以及歐美等多個(gè)國(guó)家及地區(qū)的互聯(lián)網(wǎng)數(shù)據(jù)服務(wù)公司。
- 無(wú)處不在的代碼提示;
- 靈活的攔截器;
- 可以創(chuàng)建多個(gè)實(shí)例,靈活根據(jù)項(xiàng)目進(jìn)行調(diào)整;
- 每個(gè)實(shí)例,或者說(shuō)每個(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í)例攔截器
- 接口攔截器
接下來(lái)我們就分別實(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è)簡(jiǎn)單的處理,就是將請(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是不允許我們傳入攔截器的,所以說(shuō)我們自定義了RequestConfig,讓其繼承與AxiosRequestConfig 。
剩余部分的代碼也比較簡(jiǎn)單,如下所示:
// 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)行了返回,也就是說(shuō)在request()方法中得到的類型就不是AxiosResponse類型了。
我們查看axios的index.d.ts中,對(duì)request()方法的類型定義如下:
// type.ts
request, D = any>(config: AxiosRequestConfig ): Promise ;
也就是說(shuō)它允許我們傳遞類型,從而改變r(jià)equest()方法的返回值類型,我們的代碼如下:
// index.ts
request(config: RequestConfig): Promise {
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(config)
.then(res => {
// 如果我們?yōu)閱蝹€(gè)響應(yīng)設(shè)置攔截器,這里使用單個(gè)響應(yīng)的攔截器
if (config.interceptors?.responseInterceptors) {
res = config.interceptors.responseInterceptors(res)
}
resolve(res)
})
.catch((err: any) => {
reject(err)
})
})
}
這里還存在一個(gè)細(xì)節(jié),就是我們?cè)跀r截器接受的類型一直是AxiosResponse類型,而在類攔截器中已經(jīng)將返回的類型改變,所以說(shuō)我們需要為攔截器傳遞一個(gè)泛型,從而使用這種變化,修改types.ts中的代碼,示例如下:
// index.ts
export interface RequestInterceptors {
// 請(qǐng)求攔截
requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig
requestInterceptorsCatch?: (err: any) => any
// 響應(yīng)攔截
responseInterceptors?:(config: T) => T
responseInterceptorsCatch?: (err: any) => any
}
請(qǐng)求接口攔截是最前執(zhí)行,而響應(yīng)攔截是最后執(zhí)行。
封裝請(qǐng)求方法
現(xiàn)在我們就來(lái)封裝一個(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)求方法, 來(lái)發(fā)送網(wǎng)絡(luò)請(qǐng)求,代碼如下:
// src/server/index.ts
import Request from './request'
import type { RequestConfig } from './request/types'
interface YWZRequestConfigextends RequestConfig {
data?: T
}
interface YWZResponse{
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 =(config: YWZRequestConfig ) => {
const { method = 'GET' } = config
if (method === 'get' || method === 'GET') {
config.params = config.data
}
return request.request>(config)
}
export default ywzRequest
該請(qǐng)求方式默認(rèn)為GET,且一直用data作為參數(shù);
取消請(qǐng)求
這里增加了一個(gè)取消請(qǐng)求;關(guān)于什么是取消請(qǐng)求可以參考官方文檔[1]。
準(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)槲覀兪褂胾rl做key,只有在使用的時(shí)候才知道url,所以這里使用這種語(yǔ)法。
取消請(qǐng)求方法的添加與刪除
首先我們改造一下request()方法,它需要完成兩個(gè)工作,一個(gè)就是在請(qǐng)求之前將url和取消請(qǐng)求方法push到我們前面定義的兩個(gè)屬性中,然后在請(qǐng)求完畢后(不管是失敗還是成功)都將其進(jìn)行刪除,實(shí)現(xiàn)代碼如下:
// index.ts
request(config: RequestConfig): Promise {
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(config)
.then(res => {
// 如果我們?yōu)閱蝹€(gè)響應(yīng)設(shè)置攔截器,這里使用單個(gè)響應(yīng)的攔截器
if (config.interceptors?.responseInterceptors) {
res = config.interceptors.responseInterceptors(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)求了,我們先來(lái)封裝一下取消全部請(qǐng)求吧,這個(gè)比較簡(jiǎn)單,只需要調(diào)用this.cancelRequestSourceList中的所有方法即可,實(shí)現(xiàn)代碼如下:
// index.ts
// 取消全部請(qǐng)求
cancelAllRequest() {
this.cancelRequestSourceList?.forEach(source => {
const key = Object.keys(source)[0]
source[key]( "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]( "sourceIndex][url")
} else {
// 存在多個(gè)需要取消請(qǐng)求的地址
url.forEach(u => {
const sourceIndex = this.getSourceIndex(u)
sourceIndex >= 0 && this.cancelRequestSourceList?.[sourceIndex][u]( "sourceIndex][u")
})
}
}
測(cè)試
測(cè)試請(qǐng)求方法
現(xiàn)在我們就來(lái)測(cè)試一下這個(gè)請(qǐng)求方法,這里我們使用www.apishop.net/[2]提供的免費(fèi)API進(jìn)行測(cè)試,測(cè)試代碼如下:
如果在實(shí)際開(kāi)發(fā)中可以將這些代碼分別抽離。
上面的代碼在命令中輸出
接口請(qǐng)求攔截
實(shí)例請(qǐng)求攔截器
全局請(qǐng)求攔截器
實(shí)例響應(yīng)攔截器
全局響應(yīng)攔截器
接口響應(yīng)攔截
[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
測(cè)試取消請(qǐng)求
首先我們?cè)?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è)赼pp.vue中對(duì)其進(jìn)行引用,實(shí)現(xiàn)代碼如下:
@click="cancelRequest('/api/common/weather/get15DaysWeatherByArea')" >
>取消請(qǐng)求
取消全部請(qǐng)求
發(fā)送請(qǐng)求后,點(diǎn)擊按鈕即可實(shí)現(xiàn)對(duì)應(yīng)的功能
寫(xiě)在最后
本篇文章到這里就結(jié)束了,如果文章對(duì)你有用,可以三連支持一下,如果文章中有錯(cuò)誤或者說(shuō)你有更好的見(jiàn)解,歡迎指正~
項(xiàng)目地址:ywanzhou/vue3-template (github.com)[3]
文章名稱:在項(xiàng)目中用 TS 封裝 axios ,一次封裝團(tuán)隊(duì)受益
當(dāng)前地址:http://fisionsoft.com.cn/article/coohgce.html


咨詢
建站咨詢
