axios取消接口请求
2020-04-30 17:59
615 查看
其中一个应用场景:比如说我们项目中的分页请求,如果点的快的话,一次点十几下,那么我们就会向后端发送十几个请求,这个时候,我们可以把之前还在请求的接口取消掉,只请求最后一页的数据,以免之前的数据覆盖最后请求的数据,我是在拦截器里面直接加的
let axiosList = []; let cancelToken = axios.CancelToken; let removePending = (config) => { axiosList.forEach((val,index)=>{ if(val.url == config.url){ axiosList[index].f(); axiosList.splice(index, 1); } }) } axios.interceptors.request.use( config => { if (config.url === '/' || config.url == 'http://xxxx/xxxxxx/info' || config.url == "http://xxxxxxx/xxxxxx/") { //不需要添加token的接口 } else { if (store.token) { config.headers.Authorization = store.token; } } //不需要取消请求的接口 let url = ['xxxxx', 'xxxxx', 'xxxxx'] if (!url.includes(config.url)) { removePending(config); config.cancelToken = new cancelToken((c) => { // 这里是axios标识 pending.push({ url: config.url f: c }); }); } return config; }, error => { return Promise.reject(error); }); axios.interceptors.response.use( res => { removePending(res.config); if (res.data.code == 1006 || res.data.code == 1005) { sessionStorage.clear(); router.replace({ path: '/' }); } else { return res; } }, error => { if (error.response) { switch (error.response.status) { // case 500: // sessionStorage.clear();router.replace({path:'/'});break; } } return Promise.reject(error) } );
有什么写的不对的地方欢迎批评指正
参考自:https://www.jianshu.com/p/22b49e6ad819
相关文章推荐
- vue项目axios请求接口,后端代理请求接口404,问题出现在哪?
- 为什么axios请求接口会发起两次请求
- Vue----axios 请求接口数据
- vue+axios 开发环境与生产环境配置请求接口,本地开发和线上开发有多个请求地址怎么处理?上线后自动获取ip,不需改请求地址可运用多个项目中
- axios请求失败,后端接口返回的状态码及错误信息获取
- 从 axios 源码中了解到的 Promise 链与请求的取消
- axios 请求接口报错 URLSearchParams undefined
- 为什么axios请求接口会发起两次请求(OPTIONS 和POST或者GET)
- VueJs 搭建Axios接口请求工具
- axios取消请求的实践记录分享
- 项目中常用的接口请求方式有ajax、axios、fetch,它们的区别是什么?
- 使用axios请求接口,几种content-type的区别详解
- 为什么axios请求接口会发起两次请求
- axios取消请求,取消前面一个或多个请求
- axios如何取消重复无用的请求详解
- vue项目中 axios请求拦截器与取消pending请求功能
- axios 源码分析-取消请求
- VUE -- axios 公众号授权后用后台返回的openId请求微信接口报跨域错误
- vue中使用axios请求接口,请求会发送两次
- axios 请求拦截及取消