axios AbortController 取消请求记录
axios 取消重复请求
·
import axios from 'axios'
// 创建axios实例
const http = axios.create({
baseURL: ROOT // api的base_url
})
const { isCancel } = axios
const cacheWhiteList = []
const cacheRequest = []
/**
* @desc 删除缓存队列中的请求
* @param {String} reqKey 本次请求的唯一标识 url&method
*/
function removeCacheRequest (reqKey) {
if (cacheRequest[reqKey]) {
console.log(cacheRequest, reqKey)
// 通过AbortController实例上的abort来进行请求的取消
cacheRequest[reqKey].abort()
delete cacheRequest[reqKey]
}
}
// request请求拦截
http.interceptors.request.use(requestConfig => {
const { url, method } = requestConfig
const requestKey = `${url}-${method}`
if (!cacheWhiteList.includes(requestKey)) {
removeCacheRequest(requestKey)
// 将请求加入请求队列, 通过AbortController 进行取消请求
const controller = new AbortController()
requestConfig.signal = controller.signal
cacheRequest[requestKey] = controller
}
return requestConfig
})
// response 拦截
http.interceptors.response.use((response) => {
const { url, method } = response.config
const requestKey = `${url}-${method}`
removeCacheRequest(requestKey)
return response
}, error => {
// 请求失败, 使用isCancel 判断是不是被取消的请求
if (isCancel(error)) {
return Promise.reject({
msg: '重复请求, 自动拦截取消',
message: '重复请求, 自动拦截取消'
})
}
return err
})
更多推荐
已为社区贡献2条内容
所有评论(0)