主题
防止重复请求的策略
在前端开发中,用户可能会多次点击按钮或触发同一请求,导致重复请求和冗余数据。通过 Axios 可以采用多种策略防止重复请求。
1. 使用请求标识和拦截器
javascript
import axios from "axios";
const pendingRequests = new Map();
// 添加请求拦截器
axios.interceptors.request.use((config) => {
const key = `${config.method}:${config.url}`;
if (pendingRequests.has(key)) {
// 取消重复请求
return Promise.reject(new Error("重复请求已取消"));
}
pendingRequests.set(key, true);
return config;
});
// 添加响应拦截器
axios.interceptors.response.use(
(response) => {
const key = `${response.config.method}:${response.config.url}`;
pendingRequests.delete(key);
return response;
},
(error) => {
if (error.config) {
const key = `${error.config.method}:${error.config.url}`;
pendingRequests.delete(key);
}
return Promise.reject(error);
}
);2. 使用防抖 / 节流机制
javascript
import { debounce } from "lodash";
import axios from "axios";
const fetchData = debounce(() => {
axios
.get("/search?q=keyword")
.then((res) => console.log(res.data))
.catch((err) => console.error(err));
}, 300);
// 用户快速触发搜索时,只有最后一次请求会发送
document.getElementById("searchBtn").addEventListener("click", fetchData);3. 优势
- 减少冗余请求:防止接口被重复调用;
- 提升性能:降低服务器压力,减少网络消耗;
- 改善用户体验:避免界面显示过时或重复数据。
💡 小提示:防止重复请求的策略适合搜索、表单提交、按钮点击等场景,结合拦截器和防抖/节流机制效果最佳。