当前位置:   article > 正文

前端防止重复请求_前端避免重复请求

前端避免重复请求

1,比如一个请求的延时比较大,接口比较慢,第一个请求还没有发完,第二个请求又来了,这个时候前端可以做一个控制,如果第一个请求还没有结束则关闭接下来的请求:

  1. import axios from 'axios';
  2. const CancelToken = axios.CancelToken;
  3. const requestMap = new Map();
  4. // 请求前置拦截器
  5. Axios.interceptors.request.use(
  6. config => {
  7. // 防重复提交
  8. const keyString = qs.stringify(Object.assign({}, { url: config.url, method: config.method }, config.data));
  9. if (requestMap.get(keyString)) {
  10. // 取消当前请求
  11. config.cancelToken = new CancelToken((cancel) => {
  12. cancel('Please slow down a little');
  13. });
  14. }
  15. requestMap.set(keyString, true);
  16. Object.assign(config, { _keyString: keyString });
  17. if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
  18. // 序列化
  19. config.data = qs.stringify(config.data);
  20. }
  21. return config;
  22. },
  23. error => {
  24. return Promise.reject(error);
  25. }
  26. );
  27. // 返回响应拦截器
  28. Axios.interceptors.response.use(
  29. (res: any) => {
  30. // 重置requestMap
  31. const config: any = res.config;
  32. requestMap.set(config._keyString, false);
  33. if (res.status === 200) {
  34. return res;
  35. }
  36. },
  37. error => {
  38. return Promise.reject({ error })
  39. }
  40. );

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/234513
推荐阅读
相关标签
  

闽ICP备14008679号