当前位置: 首页 > Web前端 > vue.js

vue项目封装axios请求拦截器

时间:2023-04-01 00:59:55 vue.js

axios拦截器:拦截你的每一个请求和响应,然后进行相应的处理。例如,某些网站如果在一定时间后没有运行,它们会退出并让您重新登录该页面。当然,不使用拦截器或许也能完成这个功能,但是会很麻烦,而且代码会产生很多重复,所以在项目中开发中需要使用拦截器。根据业务需要,我分为请求拦截和响应拦截。为了保证在项目中运行,先安装axios,vant.npmiaxios-snpmivant-s//后面需要用到ui库中的提示框提示拦截状态axios.jsimportaxios来自“axios”;从“vant”导入{Toast};从“../router”导入路由器;lettoken=""constbaseURL="http://localhost:1234/";//axios.defaults.baseURL=baseURL;//axios.defaults.baseURL='https://api.example.com';//设置基本路径axios.defaults.headers.common['token']=token;//设置tokenAUTH_TOKEN,将token设置为请求头axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded';//连接key的参数-值对与&,如果有空格,将空格转为加号;如果有特殊符号,则将特殊符号转换为ASCIIHEX值//vant吐司灯提示工具//Toast.clear关闭提示函数loading(){Toast.clear();Toast.loading({message:'Loading...',forbidClick:true,//forbidClick是否禁止后台点击//自定义加载图标loadingType:'spinner'});}//请求成功functionsuccess(msg){Toast.clear();Toast.success({message:msg,duration:400});}//请求失败functionfail(msg){Toast.clear();Toast.fail({message:msg,duration:400});}请求前拦截axios.interceptors.request.use(function(config){//DosomethingbeforerequestissendWhattodobeforetherequest//Configurationanimationloading();token=sessionStorage.token?sessionStorage.token:token;//设置请求头config.headers['token']=token;//前端拿到token,会把这个token(存放在sessionStorage)来配置请求头request.headers.token=tokenreturnconfig;},function(error){//DosomethingwithrequesterrorHandlerequesterrorfail("requestfailed,networkexception")returnPromise.reject(error);});//请求后的响应拦截axios.interceptors.response.use(function(response){//DosomethingwithresponsedataWhattodowiththeresponsedataconsole.log("Interceptafterenteringtherequest")console.log(response);if(response.data.code=="3000"){router.push({name:'login',query:{active:'login'}})}//类型不存在成功ss//type=0fail//type=1success//设置不同请求类型下的数据if(!!response.data.type){success(response.data.msg);}else{if(response.data.type==0){fail(response.data.msg);}else{成功(response.data.msg);}}返回响应;},function(error){//处理响应错误//处理响应错误fail("Responsefailed,serviceexception")returnPromise.reject(error);});export{axios,baseURL}//模块暴露就可以了