mpvue微信小程序的接口请求fly全局拦截代码实例
这篇文章主要介绍了mpvue微信小程序的接口请求fly全局拦截代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
业务要求:
需要进入页面时就要游客登陆拿到token;
之后的接口都是需要这个token;
其他操作则需要授权登陆,此时的token已失效;
token过久之后会过期;
业务实现:
1.全局拦截
fly.interceptors.request.use(request=>{
consttoken=storage.get('jwt')
//给所有请求添加自定义header
if(!jwt){
fly.lock()//进入接口后没有token的需要锁住请求
returnstore.dispatch('visitorLoginFun').then(res=>{//这里需要一个新的拦截器
if(res){
consttoken=storage.get('token')
request.headers['Authorization']='Bearer'+token//为队列里的接口加token
returnrequest
}
}).finally(()=>{
fly.unlock()
})
}else{
request.headers['Accept']=
'application/json,text/html;q=0.9,image/webp,*/*;q=0.8'
request.headers['Content-Type']='application/json;charset=UTF-8'
request.headers['Authorization']='Bearer'+token
request.headers['client']=client
request.headers['version']=version
wx.showNavigationBarLoading()
returnrequest
}
})
2.返回拦截
fly.interceptors.response.use(
(response,promise)=>{
if(response.data.code===1001){
mpvue.navigateTo({url:'../accredit/main'})//返回提示需要登陆需要跳转授权登陆页或者弹窗授权只能通过按钮触发
}
if(response.data.code===1002){
fly.lock()//token过期锁住拦截器
returnstore.dispatch('accreditLogin').then(res=>{//使用新起的拦截器发送登陆接口
}).finally(()=>fly.unlock()).then(()=>{
returnfly.request(response.request)//返回上一个请求
})
}
returnpromise.resolve(obj)
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。