• axios 如何取消请求?
  • 发布于 2个月前
  • 179 热度
    0 评论
问题:后端分页列表加载数据时,由于网络或者是用户点击过快的时候,请求到某页的数据不是那一页的数据。
原因:也很好理解,异步请求。
解决办法:取消上一次正在请求的相同请求(即padding状态),只保留最新一次的相同请求。

回答两个问题
1.有没有替代方法?
2.我以前为什么不做?

回答
我的做法是disabled禁用启用按钮的方式来操作。我还做过不是按钮如 tab切换的时候,请求没完成之前,不让点击。(总是不够优雅)。感觉很难完成。(事实并非如此)。下面我们就来看看实际项目中如何取消请求。

主要代码:
/* 堆代码 duidaima.com */
/* 用于区分请求,取消重复请求的时候用 */
let requestMap = new Map();

axios.interceptors.request.use(function (config) {
  // 每个请求头中添加 token
  const Token = localStorage.getItem('Authorization');
  const controller = new AbortController();
  const key = config.method + config.url;
  if (handleJudgmentRequiresCancel(config)) {
    config.signal = controller.signal;
    if (requestMap.has(key)) {
      requestMap.get(key).abort();
      requestMap.delete(key);
    } else {
      requestMap.set(key, controller);
    }
  }
  if (Token) {
    config.headers.Authorization = Token; //将token放到请求头发送给服务器
    return config;
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});
 
/* 校验请求和方法是否需要做取消上一次请求的操作 */
function handleJudgmentRequiresCancel ({ method, url }) {
  /* 白名单,允许请求多次 */
  const whiteList = ['/back/dict-config'];
  if (whiteList.includes(url)) return false;
  /* 只做get请求的取消请求 */
  if (method === 'get') return true;
  return false;
}
主要核心代码是这里
let requestMap = new Map();
const controller = new AbortController();
  const key = config.method + config.url;
  if (handleJudgmentRequiresCancel(config)) {
    config.signal = controller.signal;
    if (requestMap.has(key)) {
      requestMap.get(key).abort();
      requestMap.delete(key);
    } else {
      requestMap.set(key, controller);
    }
  }
创建了一个requestMap集合,key为请求方式和路由的组合,值为controller对象(这个对象就是用来取消请求是用到的对象)abort方法用于取消对象
handleJudgmentRequiresCancel函数,用户过滤一些请求,比如非get请求,一些可能需要重复请求,但不能取消的请求,这个方法可以根据实际情况扩展。

用上这些,基本上就可以取消请求了。在前端网络中,就可以看到一些取消的请求。做完这些,感觉还不够,因为requestMap中的数据会随着请求不同而增加,这个也好办,在响应拦截器中做相应的处理即可
axios.interceptors.response.use((response) => {
const key = response.config.method + response.config.url;
  if (handleJudgmentRequiresCancel(response.config)) {
    requestMap.delete(key);
  }
}
写完这些代码以后,感觉取消请求也不是想象中的那么难,只要能理解其中的思路,就好编写代码。既然学会了axios的取消请求,那么uniapp中有取消请求的操作吗?翻了下文档,还真有。那这样的话,一些编码就可以写的更加的优雅了。马上行动起来 。嘻嘻,又开阔了视野。
用户评论