当前位置: 首页 > Web前端 > JavaScript

axios如何实现拦截器

时间:2023-03-27 16:42:46 JavaScript

接口分析https://github.com/axios/axio...普通使用法//添加一个请求拦截器axios.interceptors.request.use(function(config){//在请求之前做一些事情sentreturnconfig;},function(error){//处理请求错误returnPromise.reject(error);});//添加响应interceptoraxios.interceptors.response.use(function(response){//Any位于2xx范围内的状态代码会导致此函数触发//对响应数据执行一些操作returnresponse;},function(error){//任何超出2xx范围的状态代码都会导致此函数触发//做一些响应错误returnPromise.reject(error);});删除拦截器constmyInterceptor=axios.interceptors.request.use(function(){/*...*/});axios.interceptors.request.eject(myInterceptor);同步处理axios.interceptors.request.use(function(config){config.headers.test='我只是一个header!';returnconfig;},null,{同步:true});条件执行函数onGetCall(config){returnconfig.method==='get';}axios.interceptors.request.use(function(config){config.headers.test='specialgetheaders';returnconfig;},null,{runWhen:onGetCall});问问题:拦截器是如何实现请求的前处理和后处理的呢?b.为什么请求拦截器要考虑同步执行呢?https://github.com/axios/axio...提到默认synchronous为false,即异步执行。当js主线程阻塞时,会导致延迟执行请求拦截器。这就涉及到事件循环模型的知识。js引擎会先执行同步代码。执行完后会查看任务队列,看是否有异步任务的结果,有则推入执行栈执行。那么我们来看看它是如何实现同步执行的。源码分析提取关键词拦截器,定位到axios.js、InterceptorManager.js查看InterceptorManager.jsprototype.use=functionuse(fulfilled,rejected,options){this.handlers.push({fulfilled:fulfilled,rejected:rejected,//是否同步执行:options?options.synchronous:false,//执行条件runWhen:选项?options.runWhen:null});returnthis.handlers.length-1;};//重置拦截器为空,注意不要删除InterceptorManager.prototype.eject=functioneject(id){if(this.handlers[id]){this.handlers[id]=null;}};//专用recursor,主要逻辑是不为null则执行executor!==null){fn(h);}});};module.exports=InterceptorManager;顺便贴一下util.js的forEach方法,本质上就是执行for循环,对每个元素执行回调函数forEach(obj,fn){//没有值就不用管了eprovidedif(obj===null||typeofobj==='undefined'){return;}//如果数组不是可迭代的,则强制数组if(typeofobj!=='object'){/*eslintno-param-reassign:0*/obj=[obj];}if(isArray(obj)){//遍历数组值for(vari=0,l=obj.length;i

最新推荐
猜你喜欢