非常简单的清除axios请求(vue,react通用)
1、添加js文件实现添加与删除接口的功能。import axios from 'axios'class CancelToken {// 声明一个 Map 用于存储每个请求的标识 和 取消函数static pending = new Map()// 白名单, 写入接口名称static whiteRequest = []/*** 得到该格式的url* @param {AxiosRequestConfi
·
1、添加js文件
实现添加与删除接口的功能。
import axios from 'axios'
class CancelToken {
// 声明一个 Map 用于存储每个请求的标识 和 取消函数
static pending = new Map()
// 白名单, 写入接口名称
static whiteRequest = []
/**
* 得到该格式的url
* @param {AxiosRequestConfig} config
* @returns
*/
static getUrl(config) {
return [config.method, config.url].join('&')
}
/**
* 添加请求
* @param {AxiosRequestConfig} config
*/
static addPending(config) {
const url = this.getUrl(config)
config.cancelToken = new axios.CancelToken(cancel => {
if (!this.pending.has(url)) { // 如果 pending 中不存在当前请求,则添加进去
this.pending.set(url, cancel)
}
})
}
/**
* 移除请求
* @param {AxiosRequestConfig} config
*/
static removePending(config) {
const url = this.getUrl(config)
const method = url.split('&')[1]
if (this.pending.has(url) && !this.whiteRequest.includes(method)) { // 如果在 pending 中存在当前请求标识,需要取消当前请求,并且移除
const cancel = this.pending.get(url)
cancel(url)
this.pending.delete(url)
}
}
/**
* 清空 pending 中的请求(在路由跳转时调用)
*/
static clearPending() {
for (const [url, cancel] of this.pending) {
cancel(url)
}
this.pending.clear()
}
}
export default CancelToken
2、实现离开页面清除请求(vue版)
利用路由的生命周期
router.beforeEach((to, from, next) => {
// 路由跳转要清除之前所有的请求缓存
CancelToken.clearPending()
next()
})
3、当请求重复时,清除上一次的请求。
利用axios 的拦截函数
import axios from 'axios'
import CancelToken from './cancalToken';
const request = axios.create({
withCredentials: false
})
request.interceptors.request.use(
config => {
// 请求开始前,检查一下是否已经有该请求了,有则取消掉该请求
CancelToken.removePending(config)
// 把当前请求添加进去
CancelToken.addPending(config)
return config
},
error => {
console.log('error', error)
return Promise.reject(new Error(error).message)
}
)
request.interceptors.response.use(
response => {
// 接口响应之后把这次请求清除
CancelToken.removePending(response.config)
console.log('.....', response)
return response.data
},
error => {
console.log('error', error)
return Promise.reject(new Error(error).message)
}
)
export default request
更多推荐
已为社区贡献2条内容
所有评论(0)