vue接口请求加密实例
1.安装vue项目npminitwebpackproject
2安装iviewnpmiiview--save(这里是结合iview框架使用的可根据自己的需求安装当然也可以不安装)
3在src目录下建一个utils文件夹里面需要放5个js都是封装好的js文件功能不仅仅局限于加密可以研究一下你会学到很多东西
1.api.js
/** *为vue实例添加http方法 *Vue.use(http) */ importhttpfrom'./http' exportdefault{ /** *install钩子 *@param{Vue}VueVue */ install(Vue){ Vue.prototype.http=http } }
2.filters.js
//公共使用的filters importVuefrom'vue'; import{getTime,getPrdType}from'../utils/time'; //区分支付方式的filter Vue.filter('paywayType',function(value){ returnvalue; }); //时间 Vue.filter('newdate',function(value){ returngetTime(value); }); //时间-分钟 Vue.filter('minute',function(str,n){ constnum=parseInt(n); returnstr.split('')[num]; }); //分割以:连接多个参数的string Vue.filter('valStr',function(str,n){ constnum=parseInt(n); returnstr.split(':')[num]; }); //根据提供时间计算倒计时 Vue.filter('countDown',function(str){ constdateStr=newDate(str).getTime(); consttimeNow=newDate().getTime(); constcountDown=dateStr-timeNow; constcountDownDay=Math.floor((dateStr-timeNow)/86400000);//计算剩余天数 constcountDownHour=Math.floor((dateStr-timeNow)/3600000%24);//计算剩余小时 constcountDownMin=Math.floor((dateStr-timeNow)/60000%60);//计算剩余分钟 //constcountDownSec=Math.floor((dateStr-timeNow)/1000%60);//计算剩余秒 if(countDown<=0){ return'----'; }else{ returncountDownDay+'天'+countDownHour+'小时'+countDownMin+'分钟'; } }); //取绝对值 Vue.filter('numberFn',function(numberStr){ returnMath.abs(numberStr); }); //处理图片地址的filter Vue.filter('imgSrc',function(src){ constenv=getPrdType(); switch(env){ case'pre': return`https://preres.bldz.com/${src}`; case'pro': return`https://res.bldz.com/${src}`; case'test': default: return`https://testimg.bldz.com/${src}`; } }); //直接转化剩余时间 Vue.filter('dateShow',function(dateStr){ constcountDownDay=Math.floor(dateStr/86400);//计算剩余天数 constcountDownHour=Math.floor(dateStr/3600%24);//计算剩余小时 constcountDownMin=Math.floor(dateStr/60%60);//计算剩余分钟 //constcountDownSec=Math.floor((dateStr-timeNow)/1000%60);//计算剩余秒 if(dateStr<=0){ return'----'; }elseif(countDownDay<=0&&countDownHour<=0){ returncountDownMin+'分钟'; }elseif(countDownDay<=0){ returncountDownHour+'小时'+countDownMin+'分钟'; }else{ returncountDownDay+'天'+countDownHour+'小时'+countDownMin+'分钟'; } }); //处理图片 Vue.filter('imgLazy',function(src){ return{ src, error:'../static/images/load-failure.png', loading:'../static/images/default-picture.png' }; }); Vue.filter('imgHandler',function(src){ returnsrc.replace(/,jpg/g,'.jpg'); });
3.http.js
importaxiosfrom'axios' importutilsfrom'../utils/utils' import{Modal}from'iview' //importqsfrom'qs'; axios.defaults.timeout=1000*60 axios.defaults.baseURL='' constdefaultHeaders={ Accept:'application/json,text/plain,*/*;charset=utf-8', 'Content-Type':'application/json;charset=utf-8', Pragma:'no-cache', 'Cache-Control':'no-cache' } //设置默认头 Object.assign(axios.defaults.headers.common,defaultHeaders) constmethods=['get','post','put','delete'] consthttp={} methods.forEach(method=>{ http[method]=axios[method].bind(axios) }) exportdefaulthttp exportconstaddRequestInterceptor= axios.interceptors.request.use.bind(axios.interceptors.request) //request前自动添加api配置 addRequestInterceptor( (config)=>{ if(utils.getlocal('token')){ //判断是否存在token,如果存在的话,则每个httpheader都加上token config.headers.Authentication=utils.getlocal('token') } //config.url=`/api${config.url}` returnconfig }, (error)=>{ returnPromise.reject(error) } ) exportconstaddResponseInterceptor= axios.interceptors.response.use.bind(axios.interceptors.response) addResponseInterceptor( (response)=>{ //在这里统一前置处理请求响应 if(Number(response.status)===200){ //全局notify有问题,还是自己处理吧 //returnPromise.reject(response.data) //window.location.href='./' //this.$router.push({path:'./'}) } returnPromise.resolve(response.data) }, (error)=>{ if(error.response){ consttitle='温馨提示'; constcontent='登录过期请重新登录
' switch(error.response.status){ case401: //返回401跳转到登录页面 Modal.error({ title:title, content:content, onOk:()=>{ localStorage.removeItem("lefthidden") localStorage.removeItem("leftlist") localStorage.removeItem("token") localStorage.removeItem("userInfo") localStorage.removeItem("headace") localStorage.removeItem("sideleft") utils.delCookie("user"); window.location.href='./' } }) break } } returnPromise.reject(error||'出错了') } )
4.time.js
//常用的工具api consttest='test'; constpre='pre'; constpro='pro'; exportfunctionjudeType(param,typeString){ if(Object.prototype.toString.call(param)===typeString)returntrue; returnfalse; }; exportfunctionisPrd(){ returnprocess.env.NODE_ENV==='production'; }; exportfunctiongetPrdType(){ returnENV; }; exportconstls={ put(key,value){ if(!key||!value)return; window.localStorage[key]=JSON.stringify(value); }, get(key){ if(!key)returnnull; consttem=window.localStorage[key]; if(!tem)returnnull; returnJSON.parse(tem); }, //设置cookie setCookie(key,value,time){ if(time){ letdate=newDate(); date.setDate(date.getDate()+time); document.cookie=key+'='+value+';expires='+date.toGMTString()+';path=/'; }else{ document.cookie=key+'='+value+';path=/'; } }, //获取cookie getCookie(key){ letarray=document.cookie.split(';'); array.map(val=>{ let[valKey,value]=val.split('='); if(valKey===key){ returndecodeURI(value); } }); return''; } }; /** *判断元素有没有该class *@param{*}el *@param{*}className */ exportfunctionhasClass(el,className){ letreg=newRegExp('(^|\\s)'+className+'(\\s|$)'); returnreg.test(el.className); } /** *为元素添加class *@param{*}el *@param{*}className */ exportfunctionaddClass(el,className){ if(hasClass(el,className))return; letnewClass=el.className.spilt(''); newClass.push(className); el.className=newClass.join(''); } exportfunctionremoveClass(el,className){ if(!hasClass(el,className))return; letreg=newRegExp('(^|\\s)'+className+'(\\s|$)','g'); el.className=el.className.replace(reg,''); } /** *将数据存储在标签里 *@param{*}el *@param{*}name *@param{*}val */ exportfunctiongetData(el,name,val){ letprefix='data-'; if(val){ returnel.setAttribute(prefix+name,val); } returnel.getAttribute(prefix+name); } exportfunctionisIphone(){ returnwindow.navigator.appVersion.match(/iphone/gi); } /** *计算元素和视窗的位置关系 *@param{*}el */ exportfunctiongetRect(el){ if(elinstanceofwindow.SVGElement){ letrect=el.getBoundingClientRect(); return{ top:rect.top, left:rect.left, width:rect.width, height:rect.height }; }else{ return{ top:el.offsetTop, left:el.offsetLeft, width:el.offsetWidth, height:el.offsetHeight }; } } /** *获取不确定数据的方法api *@param{Array}p参数数组 *@param{Object}o对象 */ exportfunctiongetIn(p,o){ returnp.reduce(function(xs,x){ return(xs&&xs[x])?xs[x]:null; },o); } /** *时间戳改为年月日格式时间 *@param{*}p时间戳 */ exportfunctiongetTime(p){ letmyDate=newDate(p); letyear=myDate.getFullYear(); letmonth=myDate.getMonth()+1; letdate=myDate.getDate(); if(month>=10){ month=''+month; }else{ month='0'+month; } if(date>=10){ date=''+date; }else{ date='0'+date; } returnyear+'-'+month+'-'+date; } exportfunctiondebounce(method,delay){ lettimer=null; returnfunction(){ letcontext=this; letargs=arguments; clearTimeout(timer); timer=setTimeout(function(){ method.apply(context,args); },delay); }; }
5utils.js
//获取cookie、 exportfunctiongetCookie(name){ if(document.cookie.length>0){ letc_start=document.cookie.indexOf(name+'=') if(c_start!=-1){ c_start=c_start+name.length+1 letc_end=document.cookie.indexOf(';',c_start) if(c_end==-1)c_end=document.cookie.length returnunescape(document.cookie.substring(c_start,c_end)) } } return'' } //设置cookie,增加到vue实例方便全局调用 exportfunctionsetCookie(cname,value,expiredays){ letexdate=newDate() exdate.setDate(exdate.getDate()+expiredays) document.cookie=cname+'='+escape(value)+((expiredays==null)?'':';expires='+exdate.toGMTString()) } //删除cookie exportfunctiondelCookie(name){ letexp=newDate() exp.setTime(exp.getTime()-1) letcval=getCookie(name) if(cval!=null){ document.cookie=name+'='+cval+';expires='+exp.toGMTString() } } //设置localstorage exportfunctionputlocal(key,value){ if(!key||!value)return window.localStorage[key]=JSON.stringify(value) } //获取localstorage exportfunctiongetlocal(key){ if(!key)returnnull consttem=window.localStorage[key] if(!tem)returnnull returnJSON.parse(tem) } /** *use_iframe_downloadfunction-通过iframe下载文件 * *@param{String}download_path需下载文件的链接 *@return{Void} */ exportconstuse_iframe_download=download_path=>{ const$iframe=document.createElement('iframe') $iframe.style.height='0px' $iframe.style.width='0px' document.body.appendChild($iframe) $iframe.setAttribute('src',download_path) setTimeout(function(){$iframe.remove()},20000) } functionrequestTimeout(xhr){ consttimer=setTimeout(()=>{ timer&&clearTimeout(timer) xhr.abort() },5000) returntimer } //导出 exportfunctionexporttable(httpUrl,token,formData,callback){ leti=formData.entries(); letparam="?Authentication="+token; do{ varv=i.next(); if(!v.done){ param+="&"+v.value[0]+"="+v.value[1]; } }while(!v.done); //console.log(param); window.open(httpUrl+param) //varxhr=newXMLHttpRequest() //if(xhr.withCredentials===undefined){ //returnfalse //}; //xhr.open("post",httpUrl) ////xhr.timeout=5000 //xhr.setRequestHeader("Authentication",token) //xhr.responseType="blob" //lettimer=requestTimeout(xhr) //xhr.onreadystatechange=function(){ //timer&&clearTimeout(timer) //if(xhr.readyState!==4){ //timer=requestTimeout(xhr) //return //} //if(this.status===200){ //varblob=this.response //varcontentType=this.getResponseHeader('content-type') //varfileName=contentType.split(";")[1].split("=")[1] //fileName=decodeURI(fileName) //letaTag=document.createElement('a') ////下载的文件名 //aTag.download=fileName //aTag.href=URL.createObjectURL(blob) //aTag.click() //URL.revokeObjectURL(blob) callback&&callback(true) //}else{ //callback&&callback(false) //} //} //xhr.send(formData); } //获取当前时间 exportfunctiongetNowFormatDate(){ vardate=newDate(); varseperator1="-"; varseperator2=":"; varmonth=date.getMonth()+1; varstrDate=date.getDate(); if(month>=1&&month<=9){ month="0"+month; } if(strDate>=0&&strDate<=9){ strDate="0"+strDate; } varcurrentdate=date.getFullYear()+seperator1+month+seperator1+strDate +""+date.getHours()+seperator2+date.getMinutes() +seperator2+date.getSeconds(); returncurrentdate; } //时间格式化 exportfunctionformatDate(date,fmt){ if(/(y+)/.test(fmt)){ fmt=fmt.replace(RegExp.$1,(date.getFullYear()+'').substr(4-RegExp.$1.length)); } leto={ 'M+':date.getMonth()+1, 'd+':date.getDate(), 'h+':date.getHours(), 'm+':date.getMinutes(), 's+':date.getSeconds() }; for(letkino){ if(newRegExp(`(${k})`).test(fmt)){ letstr=o[k]+''; fmt=fmt.replace(RegExp.$1,(RegExp.$1.length===1)?str:padLeftZero(str)); } } returnfmt; }; functionpadLeftZero(str){ return('00'+str).substr(str.length); } exportdefault{ getCookie, setCookie, delCookie, putlocal, getlocal, exporttable, getNowFormatDate, formatDate }
4.配置main.js
importVuefrom'vue' importAppfrom'./App' importrouterfrom'./router' importVueRouterfrom'vue-router'; importiViewfrom'iview'; import'iview/dist/styles/iview.css' importhttpfrom'./utils/http' importApifrom'./utils/api' importutilsfrom'./utils/utils' import'./utils/filters' Vue.config.productionTip=false Vue.use(VueRouter); Vue.use(iView); Vue.use(http) Vue.use(Api) Vue.use(utils) /*eslint-disableno-new*/ global.BASE_URL=process.env.API_HOST newVue({ el:'#app', router, components:{App}, template:'' })
5.找到config文件夹下的dev.env.js
module.exports=merge(prodEnv,{ NODE_ENV:'"development"', API_HOST:'"开发环境接口地址"' })
6.页面中具体使用方法
{{item.productName}}
以上这篇vue接口请求加密实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。