码迷,mamicode.com
首页 > 微信 > 详细

mpvue微信小程序的接口请求fly之全局拦截

时间:2019-11-12 20:11:04      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:patch   ons   show   charset   vue   ima   接口   The   log   

业务要求:

  需要进入页面时就要游客登陆拿到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)
      }
    }
 

mpvue微信小程序的接口请求fly之全局拦截

标签:patch   ons   show   charset   vue   ima   接口   The   log   

原文地址:https://www.cnblogs.com/pyramid/p/11844525.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!