防止重复提交请求

前景提要:
ts 简易封装 axios,统一 API
实现在 config 中配置开关拦截器
axios 实现请求 loading 效果

用一个数组保存当前请求的 url,此时还未响应。如果再次发起同样请求,比对 url 发现已经存在数组中,则拦截请求,提示重复提交。当该请求响应结束后,就将 url 从数组中剔除。则可再次发起上一次 url 的请求。

封装拦截器

typescript 复制代码
import { AxiosError } from "axios";
import { ElMessage } from "element-plus";
import { MyAxiosResponse, MyInternalAxiosRequestConfig } from "./request";

let pendingUrl: string[] = []; // pending 状态的请求 url
const excludeUrl: string[] = ["/upload", "/upload/chunk"]; // 排除不需要拦截的url。比如并发上传文件的 url 都是一样的,就需要排除

/**
 * 比较请求的 url
 * @param {import("..").AxiosRequestConfig} config
 * @returns
 */
export function compareUrl(config: MyInternalAxiosRequestConfig) {
    // 配置中明确标出 debounce 为 false,则关闭请求防抖。不写或者为 true,则开启防抖
    if (config.debounce === false) return config;

    // 白名单 url 不防抖处理
    if (config.url && excludeUrl.includes(config.url)) return config;

    if (config.url && pendingUrl.includes(config.url)) {
        // alert("重复请求");
        ElMessage.warning("请求频繁");
        throw new Error("请求频繁");
    } else {
        config.url && pendingUrl.push(config.url);
    }
    return config;
}

/**
 * 请求成功,过滤请求完毕的 url
 * @param {import("axios").AxiosResponse} res
 * @returns
 */
export function filterFulfilledUrlOnFulfilled(res: MyAxiosResponse) {
    pendingUrl = pendingUrl.filter(item => item != res.config.url);
    return res;
}

/**
 * 请求错误,过滤请求完毕的 url
 * @param {import("axios").AxiosError} err
 * @returns
 */
export function filterFulfilledUrlOnRejected(err: AxiosError) {
    pendingUrl = pendingUrl.filter(item => item != err?.config?.url);
    throw err;
}

补充 config 配置并注册拦截器

typescript 复制代码
const DEFAULT_EXTRA_FEATURE_CONFIG = { showLoading: true, showMessage: true, debounce: true, retry: true };

/** 扩展 axios 的请求配置类型 */
export interface MyAxiosRequestConfig<TReqBodyData = any> extends AxiosRequestConfig<TReqBodyData> {
    interceptors?: {
        reqInterceptorOnFulfilled?: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig;
        reqInterceptorOnRejected?: (err: AxiosError) => any;
        resInterceptorOnFulfilled?: (res: AxiosResponse) => AxiosResponse;
        resInterceptorOnRejected?: (err: AxiosError) => Promise<AxiosError>;
    };
    showLoading?: boolean;
    showMessage?: boolean;
    debounce?: boolean;
    retry?: boolean;
}

/** 给拦截器使用 */
export interface MyInternalAxiosRequestConfig extends InternalAxiosRequestConfig {
    showLoading?: boolean;
    showMessage?: boolean;
    debounce?: boolean;
    retry?: boolean;
}
typescript 复制代码
import HttpRequest from "./http/request";
import { compareUrl, filterFulfilledUrlOnFulfilled, filterFulfilledUrlOnRejected } from "./http/debounceReq";
import { closeLoadingOnFulfilled, closeLoadingOnRejected, showLoading } from "./http/loading";
import { responseMessageOnFulfilled } from "./http/message";
import { getTokenResponseInterceptor, setAccessTokenRequestInterceptor } from "./http/token";
import { retryRequest } from "./http/retryRequest";

const httpRequest = new HttpRequest({
    baseURL: import.meta.env.VITE_APP_API_BASE_URL,
    timeout: import.meta.env.VITE_APP_API_TIMEOUT
});

// loading
httpRequest.getInstance().interceptors.request.use(showLoading);
httpRequest.getInstance().interceptors.response.use(closeLoadingOnFulfilled, closeLoadingOnRejected);

// debounceRequest
httpRequest.getInstance().interceptors.request.use(compareUrl);
httpRequest.getInstance().interceptors.response.use(filterFulfilledUrlOnFulfilled, filterFulfilledUrlOnRejected);

export default httpRequest;
``
相关推荐
爱的叹息8 分钟前
【前端】基于 Promise 的 HTTP 客户端工具Axios 详解
前端·网络·网络协议·http
遗憾随她而去.15 分钟前
从 0 开始认识 WebSocket:前端实时通信的利器!
前端·websocket·网络协议
老兵发新帖1 小时前
pnpm常见报错解决办法
前端
Sonetto19991 小时前
Nginx 反向代理,啥是“反向代理“啊,为啥叫“反向“代理?而不叫“正向”代理?它能干哈?
运维·前端·nginx
沐土Arvin1 小时前
理解npm的工作原理:优化你的项目依赖管理流程
开发语言·前端·javascript·设计模式·npm·node.js
好_快1 小时前
Lodash源码阅读-baseUniq
前端·javascript·源码阅读
不秃的开发媛1 小时前
前端技术Ajax入门
java·开发语言·前端
牧羊狼的狼1 小时前
React.memo 和 useMemo
前端·javascript·react.js
xixixin_1 小时前
【uniapp】vue2 搜索文字高亮显示
java·服务器·前端·uni-app·交互·文字高亮
还是鼠鼠1 小时前
Android移动应用开发入门示例:Activity跳转界面
android·前端·gitee·android studio·android-studio