进击的crab最近项目接口比较多,为了方便统一管理,写了这个一个玩意,统一管理接口地址,cookie,添加请求头token等。可以防抖和显示全局加载界面。 以后crab君还会把有趣的编程知识分享给大家,希望大家点赞支持。防抖letpending〔〕;声明一个数组用于存储每个ajax请求的取消函数和ajax标识letcancelTokenaxios。CancelTletremovePending(config){for(letpinpending){if(pending〔p〕。uconfig。urlconfig。method){当前请求在数组中存在时执行函数体pending〔p〕。f();执行取消操作pending。splice(p,1);把这条记录从数组中移除}}};全局loading当前正在请求的数量letrequestCount0;显示loadingfunctionshowLoading(){if(requestCount0){vardomdocument。createElement(p);dom。setAttribute(id,loading);document。body。appendChild(dom);ReactDOM。render(Spintip加载中。。。sizelarge,dom);}requestC}隐藏loadingfunctionhideLoading(){requestCif(requestCount0){document。body。removeChild(document。getElementById(loading));}}axios。defaults。baseURL;填写你访问的默认地址axios。defaults。withC设置cross跨域并设置访问权限允许跨域携带cookie信息axios。interceptors。request。use(function(config){在发送请求之前做些什么console。log(请求前拦截,config)removePending(config);在一个ajax发送前执行一下取消操作config。cancelTokennewcancelToken((c){console。log(config。url)这里的ajax标识我是用请求地址请求方式拼接的字符串,当然你可以选择其他的一些方式pending。push({u:config。urlconfig。method,f:c});});lettokengetSession(Token);if(token){config。headers〔Token〕}开启loadingrequestCount为0,才创建loading,避免重复创建if(config。isLoading!false){showLoading();}},function(error){对请求错误做些什么console。log(请求前拦截err)判断当前请求是否设置了不显示Loadingif(error。config。isLoading!false){hideLoading();}returnPromise。reject(error);});添加响应拦截器axios。interceptors。response。use(function(response){对响应数据做点什么console。log(响应拦截)removePending(response。config);在一个ajax响应后再执行一下取消操作,把已经完成的请求从pending中移除hideLoading();},function(error){对响应错误做点什么console。log(响应拦截err);hideLoading();returnPromise。reject(error);});