对微信小程序网络请求框架的再次封装

微信小程序的网络请求框架已经设计得很简单易用了,它是这样发起网络请求的:

wx.request({
  url: 'test.php', //仅为示例,并非真实的接口地址
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' // 默认值
  },
  success (res) {
    console.log(res.data)
  }
})

但是我们最好还是要对它再进行一次封装,因为我们很多时候需要一个统一的网络请求处理,比如token过期,网络错误处理等等,所以我用Promise对微信的网络请求框架做了一个简单的封装。把网络请求的代码封装到util.js文件中,比如可以写一个方法叫requestData:

const API_BASE_URL = 'https://api.test.com:8080'

const app = getApp()

const requestData = (path, method, data) => {
  return new Promise(function(resolve, reject) {
    var token = app.globalData.token
    if (token == null) {
      token = wx.getStorageSync('token') ? wx.getStorageSync('token') : ''
    }
    wx.request({
      url: API_BASE_URL + path,
      data: data,
      method: method,
      header: {
        'content-type': 'application/json',
        'token': token
      },
      success: function(res) {
        // cookies:"",data:"",errMsg:"request:ok",header:{Connection: "Keep-Alive", … },statusCode:200
        if (res.data.result || false) {
          resolve(res.data)
        } else {
          var e = new Object();
          if (res.data.errorCode == 30000) {
            //校验token失效
            getNewToken()
            e.errMsg = "登录失效,请刷新重试"
          } else if (res.data.errorCode == 30001) {
            //没有绑定手机号
            bindPhone()
            e.errMsg = "尚未绑定手机号"
          } else {
            e.errMsg = res.data.message || "请求失败"
          }
          reject(e)
        }
      },
      fail: function(e) {
        //e = { errMsg: "request:fail invalid url" }
        e.errMsg = "网络请求失败"
        reject(e)
      }
    })
  })
}

再定义一下get 和 post 方法,然后export出来:

function getData(path, data) {
  return requestData(path, 'GET', data)
}

function postData(path, data) {
  return requestData(path, 'POST', data)
}


module.exports = {
  GET: getData,
  POST: postData
}

然后在需要用到网络请求的js文件中引入即可

const API = require('../../../utils/util.js')

submit: function(e) {
    wx.showLoading({
      title: '提交中...',
    });
    API.POST("/room/visit", {
      visitTime: '2019-06-01 18:00:00',
      roomId: this.data.room.roomId,
      visitorName: name,
      visitorPhone: phone
    }).then(res => {//数据请求成功
      wx.hideLoading();
      wx.showToast({
        title: '预约成功'
      })
    }).catch(res => {//数据请求失败
      wx.hideLoading();
      wx.showToast({
        title: res.errMsg,
        icon: 'none'
      })
    });
  },

这个网络工具类还有上传图片和批量上传图片等功能,完整文件请访问:

https://github.com/tigerchou/mputils

发布了27 篇原创文章 · 获赞 24 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/shving/article/details/102713749