当前位置:首页 > 微信 > 正文

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

11-25 微信

标签: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.jmwww.net/weixin/15561.html

博客主人杰米WWW
杰米博客,为大家提供seo以及it方面技巧喜欢的朋友收藏哦!
  • 11365文章总数
  • 2266821访问次数
  • 建站天数
  • 头条文章

    图文推荐

    站长推荐

    友情链接