axios 配置 adapter, 設(shè)置自定義請(qǐng)求方法
在 axios 配置中提供了[adapter]配置項(xiàng),
使用該配置項(xiàng)目, 我們可以設(shè)置屬于自己的請(qǐng)求方法.
請(qǐng)求流程
- req: 發(fā)起請(qǐng)求
- reqContext: 包裝請(qǐng)求上下文
- adapter: 分發(fā)
- dispath: 底層請(qǐng)求接口
- server: 服務(wù)器
- res: 響應(yīng)處理
graph LR
req-->reqContext
reqContext-->adapter
adapter-->dispath
dispath-->server
server-->dispath
dispath-->adapter
adapter-->res
從流程圖,我們大致知道 adapter 的調(diào)用位置, 可以看到 adapter
是連接 請(qǐng)求與響應(yīng)的橋梁
默認(rèn) adapter
在未配置adapter時(shí), axios將提供默認(rèn)配置
// 默認(rèn)配合
var defaults = {
adapter: getDefaultAdapter()
....
}
// 分發(fā)函數(shù)
function getDefaultAdapter() {
var adapter;
if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
// node環(huán)境下使用 node.http
adapter = require('./adapters/http');
} else if (typeof XMLHttpRequest !== 'undefined') {
// web 環(huán)境下使用 xhr
adapter = require('./adapters/xhr');
}
return adapter;
}
這里我們看到,adapter 主要根據(jù)環(huán)境不同,調(diào)用不同請(qǐng)求接口,并將數(shù)據(jù)返回給響應(yīng)函數(shù).
啟示
- 整個(gè)請(qǐng)求過程是線性的,不存在路由分發(fā)的機(jī)制
- 通過 adapter 我們可以直接控制 請(qǐng)求及響應(yīng).
使用 adapter 做mock
這里只做實(shí)現(xiàn)的基本模式,在配置 adapter 可能遇到的問題s
// mock數(shù)據(jù)路由,根據(jù)url 返回mock數(shù)據(jù)
const mockRouter = {...}
const http = Axios.create({
adapter: config =>{
// 判斷是否存在mock數(shù)據(jù)
let has = mockRouter.has(config.url)
// 調(diào)用默認(rèn)請(qǐng)求接口, 發(fā)送正常請(qǐng)求及返回
if(!data){
// 刪除配置中的 adapter, 使用默認(rèn)值
delete config.adapter
// 通過配置發(fā)起請(qǐng)求
return Axios(config)
}
// 模擬服務(wù),返回mock數(shù)據(jù)
return new Promise((res, rej) =>{
const resInfo = {
data: mockRouter.getData(config)
status: 200,
statusText: 'OK'
}
// 調(diào)用響應(yīng)函數(shù)
res(resInfo)
})
}
})
這里需要注意的是,在使用配置發(fā)起請(qǐng)求時(shí),需要?jiǎng)h除config中的 自定義adapter, 使用的aixos調(diào)用默認(rèn)請(qǐng)求接口.
否則將進(jìn)入遞歸的死循環(huán)