这篇文章主要介绍了mpvue微信小程序的接口请求fly全局拦截代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
业务要求:
需要进入页面时就要游客登陆拿到token;
之后的接口都是需要这个token;
其他操作则需要授权登陆,此时的token已失效;
token过久之后会过期;
业务实现:
1.全局拦截
- fly.interceptors.request.use(request => {
- const token = storage.get('jwt')
- // 给所有请求添加自定义header
- if (!jwt) {
- fly.lock() // 进入接口后没有token的需要锁住请求
- return store.dispatch('visitorLoginFun').then(res => { // 这里需要一个新的拦截器
- if (res) {
- const token = storage.get('token')
- request.headers['Authorization'] = 'Bearer ' + token // 为队列里的接口加token
- return request
- }
- }).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()
- return request
- }
- })
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过期 锁住拦截器
- return store.dispatch('accreditLogin').then(res => { // 使用新起的拦截器发送登陆接口
- }).finally(() => fly.unlock()).then(() => {
- return fly.request(response.request) // 返回上一个请求
- })
- }
- return promise.resolve(obj)
- }
- }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。