在工作业务中,由于遇到了需要持续请求获取当前状态的场景,本来是考虑使用 WebSocket ,无奈后端不肯配合使用,于是乎网上查找 axios 有没有比较简便的集成方案,赶紧都不大满意,所以自己封装了一个基于 axios 简单,快捷的 axios 轮询插件。
轮询就不多介绍了,简单来算就是在一段时间间隔持续请求后端的接口,到指定条件时停止请求,刚刚看了一篇文章,大概意思就是这样
前台:后台你好了没有?(3秒后。。。)
后台:没有。
前台:后台你好了没有?(3秒后。。。)
后台:没有。
前台:后台你好了没有?(3秒后。。。)
后台:好了。。
当然,有条件最好还是用 WebSocket 吧,轮询相对来说还是有很多缺点的。
axios-polling:TuiMao233/axios-polling
Blog:www.hairy.blog/
使用 axios-polling
axios-polling 是一个简单,快捷的 axios 轮询扩展,并且可继承当前 axios 配置。
npm & ESM 安装
npm i axios axios-polling
introduce 使用
import axios from 'axios'
import { axiosPolling } from 'axios-polling'
// 初始化 axios-polling
axiosPolling(axios, {
retryLimit: 15
})
// 后续编辑轮询配置
axios.defaults.polling['retryLimit'] = 20
// 创建轮询请求
const { emit, on, off, remove } = axios.poll({
url: '/message',
params: { id: 1 }
})
// 发送轮询请求
// emit 配置会与 poll 配置合并, emit 配置优先
emit({ params: { id: 2 } })
// 监听发送请求前
on('request', (config) => {
console.log(config.polling.count)
})
// 监听发送请求后
on('response', (response) => {
console.log(response)
})
// 监听请求失败
on('error', (error) => {
console.log(response)
})
// 关闭轮询请求
off()
// 移除所有 on 监听队列
remove()
config 配置
interface AxiosPollingConfig {
/** 当前正常轮询的总次数,初始值:0 */
count: number
/** 正常轮询时,请求延迟毫秒数,默认:1000毫秒 */
dalay: number
/** 轮询请求间隔递增毫秒数,默认:0毫秒(建议不要超过1000) */
delayGaps: number
/** 发生错误时,当前已重试的次数,初始值:0 */
retryCount: number
/** 当发生错误时请求的最大次数,默认:10次 */
retryLimit: number
/** 第一次发送请求毫秒数,默认:1000毫秒 */
retryAfter: number
}