1

之前在写公司小程序时由于大部分接口都需要传入token参数,为了方便,将请求API进行封装,实现每次发送请求会同时自己添加token参数。这里做个记录避免以后忘了怎么写←_←

根目录创建utils目录,该目录下面添加一个js文件,文件名随意

var app = getApp()

//相同前缀的url
const baseUrl = app.globalData.url

function fun(url, method, data, header) {
  data = data || {}
  header = header || {}
  method = method

  let promise = new Promise(function(resolve, reject) {
    wx.request({
      url: baseUrl + url,
      header: header,
      //每个请求都提前自动传递token
      data: Object.assign({
        _token: app.globalData.token
      }, data),
      method: method,
      success: function(res) {
      //响应拦截
        console.log(res)
        //通过返回的code参数的不同进行后续不同的操作
        if (res.data.code) {
        //我们后台规定当code为110时,就代表当前没有登录
          if (res.data.code === 110) {
            util.showMessage('登录失效,请重新登录')
            setTimeout(() => {
            //跳转到登录页面
              wx.reLaunch({
                url: '../login/login'
              })
            }, 1000)
            reject(res)
          } else if (res.data.responseCode) {
            let responseCode = res.data.responseCode

            //处理未绑定微信的情况
            if (responseCode === 103) {
                  wx.hideToast();
                  wx.showModal({
                    content: `${app.globalData.responseCode[responseCode]},即将转到微信绑定页面`,
                    showCancel: false,
                    confirmText: "确定",
                    success() {
                      //转到绑定微信页面
                        wx.reLaunch({
                          url: '../bind/bind'
                        })
                    }
                  })
     
              reject(res)
            } else {
              //其他情况,把响应编码对应的提示信息已弹出框形式告知用户
              wx.hideToast();
                  wx.showModal({
                    content: `${app.globalData.responseCode[responseCode]}`,
                    showCancel: false,
                    confirmText: "确定"
                  })
            }
          }
        }
        resolve(res)
      },
      fail: function(err) {
        reject(err)
      },
      complete: function() {
        //不管是success还是fail都会走这里的函数
        wx.hideToast()
      }
    })
  })
  return promise
}

//导出模块
module.exports = {
  baseUrl: baseUrl,
  "get": function(url, data, header) {
    return fun(url, "get", data, {
      'content-type': 'application/x-www-form-urlencoded'
    });
  },
  "post": function(url, data, header) {
    return fun(url, "post", data, {
      'content-type': 'application/x-www-form-urlencoded'
    })
  },
  "put": function(url, data, header) {
    return fun(url, "put", data, header);
  },
  "delete": function(url, data, header) {
    return fun(url, "delete", data, header);
  }
}

使用时

//引入
const request = require('../../utils/http')

//使用get方法
request.get("admin/sigin/getDistance", {
   lat: '111',
   lng: '111'
})
    .tnen(){}
    .catch(){}

君额上似可跑马
39 声望4 粉丝