axios拦截重复请求
程序员文章站
2022-03-13 21:33:15
不多BB直接上代码import axios from 'axios';/* 初始化axios实例 */const service = axios.create({ baseURL: process.env.VUE_APP_BASEURL, headers: {'Content-Type': 'application/json'}, timeout: 10 * 1000, withCredentials: true})需要注意的点,请看注释/* 拦截重复请求 */...
不多BB直接上代码
import axios from 'axios';
/* 初始化axios实例 */
const service = axios.create({
baseURL: process.env.VUE_APP_BASEURL,
headers: {'Content-Type': 'application/json'},
timeout: 10 * 1000,
withCredentials: true //创建一个跨站点访问控制(cross-site Access-Control)请求,具体看业务
})
需要注意的点,请看注释
/* 拦截重复请求 */
const pending = {}
/* 需要注意的是这里 一定要写成axios.CancelToken,不要在axios实例(我现在这* 个例子axios实例是service)
* 上取CancelToken,取不到的*/
const CancelToken = axios.CancelToken
const removePending = (key, isRequest = false) => {
if (pending[key] && isRequest) {
pending[key]('取消重复请求')
}
delete pending[key]
}
const getRequestIdentify = (config, isReuest = false) => {
let url = config.url
if (isReuest) {
url = config.baseURL + config.url.substring(1, config.url.length)
}
return (
config.method === 'get'
? encodeURIComponent(url + JSON.stringify(config.params))
: encodeURIComponent(config.url + JSON.stringify(config.data))
)
}
在请求拦截器里使用
service.interceptors.request.use(
config => {
// 拦截重复请求(即当前正在进行的相同请求)
let requestData = getRequestIdentify(config, true)
removePending(requestData, true)
config.cancelToken = new CancelToken((c) => {
pending[requestData] = c
})
return config
},
error => {
console.log('request:', error)// 请求错误时 for debug
return Promise.reject(error)
}
)
参考文档:https://segmentfault.com/a/1190000016457844
本文地址:https://blog.csdn.net/qq_42031498/article/details/110630236