vite + ts + axios 实现防止同个接口在2秒内重复提交
时间: 2023-11-25 20:41:41 浏览: 88
可以通过封装一个请求拦截器来实现。在请求时,先判断该接口是否已经在请求中,并记录当前接口的请求标识。在接口返回后,清除该接口的请求标识。若该接口在2秒内再次请求,则直接取消该请求。
以下是示例代码:
```typescript
import Axios, { AxiosInstance } from 'axios';
const axiosInstance: AxiosInstance = Axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
});
const pendingRequests = new Map<string, Function>();
const cancelPendingRequests = (config: any) => {
const cancelToken = JSON.stringify({
method: config.method,
url: config.url,
params: config.params,
data: config.data,
});
if (pendingRequests.has(cancelToken)) {
const cancel = pendingRequests.get(cancelToken);
cancel();
pendingRequests.delete(cancelToken);
}
const cancel = Axios.CancelToken.source();
config.cancelToken = cancel.token;
pendingRequests.set(cancelToken, cancel.cancel);
};
axiosInstance.interceptors.request.use((config) => {
cancelPendingRequests(config);
return config;
});
axiosInstance.interceptors.response.use((response) => {
const cancelToken = JSON.stringify({
method: response.config.method,
url: response.config.url,
params: response.config.params,
data: response.config.data,
});
pendingRequests.delete(cancelToken);
return response;
});
export default axiosInstance;
```
在发起请求时,需要将接口的请求标识设置为该接口的请求参数或请求体,例如:
```typescript
import axios from './axios';
const fetchData = async () => {
const requestConfig = {
method: 'post',
url: '/data',
data: {
id: '123',
name: 'example',
},
};
try {
const response = await axios(requestConfig);
console.log(response.data);
} catch (error) {
console.error(error);
}
};
fetchData();
```
阅读全文