微信小程序 封装post请求 header加token code码拦截

1.添加一个js文件  例如:class/api/Post.js

2.编写js文件  例:token我存在用户信息 17000用户信息过期

3.引用 app.js

4.页面使用

代码:

export default class Post {
  constructor() { }

  request = (path, data) => {
    let app = getApp(),
      url = `${app.globalData.api}${path}`,
      header = {
        token: wx.getStorageSync('user').token || '',
        'content-type': 'application/x-www-form-urlencoded'
      }
    var promise = new Promise((resolve, reject) => {
      wx.request({
        url: url,
        data: data,
        method: "POST",
        header: header,
        success(res) {
          console.log('res 响应拦截', res.data.code)
          if (res.data.code == 17000) {
            wx.showModal({
              title: '提示',
              content: '授权已过期或未授权!请重新授权!',
              showCancel: true,
              cancelText: "返回首页",
              confirmText: "去授权",
              success: (res) => {
                res.cancel ?
                  wx.switchTab({
                    url: '/pages/index/index',
                  }) :
                  wx.navigateTo({
                    url: '/pages/login/login',
                  })
              },
              fail: res => { }
            })
          }
          return resolve(res)
        },
        fail: reject
      })
    });
    return promise;
  }
}

import Post from './class/api/Post.js'

const post = new Post();

App({

  post: post,
  onLaunch: function () {
 
    const updateManager = wx.getUpdateManager()
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好,是否重启应用?',
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })



  },
  globalData: {
    api: Config.api,
    userInfo: null
  }
})
 app.post.request('api', {
      pageNum: 1,
      type: 0,
      lat: 29.03158,
      lon: 111.69854
    })
      .then(res => {
        console.log('responent', res)
        
      })

 

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值