赞
踩
1,比如一个请求的延时比较大,接口比较慢,第一个请求还没有发完,第二个请求又来了,这个时候前端可以做一个控制,如果第一个请求还没有结束则关闭接下来的请求:
- import axios from 'axios';
-
- const CancelToken = axios.CancelToken;
- const requestMap = new Map();
-
- // 请求前置拦截器
- Axios.interceptors.request.use(
- config => {
- // 防重复提交
- const keyString = qs.stringify(Object.assign({}, { url: config.url, method: config.method }, config.data));
- if (requestMap.get(keyString)) {
- // 取消当前请求
- config.cancelToken = new CancelToken((cancel) => {
- cancel('Please slow down a little');
- });
- }
- requestMap.set(keyString, true);
- Object.assign(config, { _keyString: keyString });
-
- if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
- // 序列化
- config.data = qs.stringify(config.data);
- }
- return config;
- },
- error => {
- return Promise.reject(error);
- }
- );
-
- // 返回响应拦截器
- Axios.interceptors.response.use(
- (res: any) => {
- // 重置requestMap
- const config: any = res.config;
- requestMap.set(config._keyString, false);
- if (res.status === 200) {
- return res;
- }
- },
- error => {
- return Promise.reject({ error })
- }
- );
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。