这篇文章主要是想记录下之前遇到的jwt过期,前端封装请求处理jwt过期问题。//将请求统一打包在文件request.jsimport{AxiosStatus}from'axios-status';importaxiosfrom'axios';importutilsfrom'../util';//暂停请求数组letrefreshSubscribers=[];//是否有请求刷新tokenwindow.isRefreshing=false;constaxiosStatus=newAxiosStatus({timeout:20,//默认10autoRetry:false//默认false});axiosStatus.register(axios);函数resendCatchedRequest(){constlist=refreshSubscribers;刷新订阅者=[];window.isRefreshing=false;if(!list||!list.length){return}list.forEach((item)=>{postRequest(item.url,item.opts).then((...args)=>{item.resolveHandler&&item.resolveHandler(...args)}).catch((...args)=>{item.rejectHandler&&item.rejectHandler(...args)})})}asyncfunctionpostRequest(url,opts={}){letjwt=awaitutils.freshJWT();//获取jwt如果(!opts['headers']){opts['headers']={}}opts['headers']['Content-Type']='application/json';opts['headers']['jwt']=jwt;returnaxiosStatus.request({url:url,method:opts['method']||'get',baseURL:opts['baseURL'],headers:opts['headers'],params:opts['params'],data:opts['data'],timeout:10000,withCredentials:false,cancelToken:opts['cancelToken'],success:(res)=>{if(res.status!==200){返回{代码:res.status,msg:res.statusText}}//服务端通知jwt过期if(res.data.code==1004){returnnewPromise((resolve,reject)=>{refreshSubscribers.push({url:url,选择:选择,resolveHandler:解决,rejectHandler:拒绝,});window.isRefreshing=true;//从方法中返回最新的jwt值以覆盖localStorage中的原始值API.login().then(data=>{window.localStorage.setItem('jwt',data.jwt);resendCatchedRequest();})})}returnres.data},error:()=>{//console.log('inerror',error)}})}exportdefault{postRequest,}
