封装微信小程序api - wx.request

  • fetch.js 最底层封装
  // https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-request.html
module.exports = function (url, method, data, params) {
  let user
  try {
    user = wx.getStorageSync('user')
  } catch (e) {
    wx.showModal({
      content: `用户信息读取失败`,
      showCancel: false
    })
  }
  let headers = {'content-type': 'application/json'}
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '加载中'
    })
    wx.showNavigationBarLoading()

    const URL = url + urlEncode(params)
    console.log('[HTTP]', method, URL)
    wx.request({
      url: URL,
      method: method,
      data: Object.assign({}, data),
      header: headers,
      success: res => {
        wx.hideLoading()
        wx.hideNavigationBarLoading()
        if (res.statusCode >= 400 && res.statusCode < 600) {
          if (res.statusCode === 401) {
            wx.clearStorage()
            wx.reLaunch({
              url: '/pages/login/login'
            })
            wx.showToast({
              icon: 'loading',
              title: '请重新登录'
            })
          } else {
            console.log('fetch error', res)
            reject(res)
          }
        } else {
          resolve(res)
        }
      },
      fail: error => {
        wx.hideLoading()
        console.log('fetch error', error)
      }
    })
  })
}

function urlEncode (params) {
  if (params) {
    var result = '?'
    for (let key in params) {
      result += `${key}=${params[key]}&`
    }
    return result
  }
  return ''
}
  • http.js 封装GET,POST,PUT,DELETE四种方法
// 填写自己的host,注意相对路径
const {host} = require('../config')
const fetch = require('./fetch')

const http = {
  get (url, params) {
    return fetch(host + url, 'GET', null, params)
  },
  post (url, body, params) {
    return fetch(host + url, 'POST', body, params)
  },
  put (url, body, params) {
    return fetch(host + url, 'PUT', body, params)
  },
  delete (url, params) {
    return fetch(host + url, 'DELETE', null, params)
  }
}
module.exports = http
  • 业务api - answer.js
const http = require('./http')
const res = {
  /**
   * 查询所有的问题列表
   */
  queryAllQuestions (range, page, size) {
    return http.get(`/v1/questions`, {range: range, page: page, size: size, action: 'all'})
  },
  // 其他方法
  xxxx(){
  }
}
module.exports = res
  • page里的调用方 question-answer.js
// 获取全局应用程序实例对象
// const app = getApp()
// 引入业务js
const answerRes = require('../../api/answer')

// 创建页面实例对象
Page(Object.assign({}, {
  data:{
    page:1,
    size:10
  },
  queryAllQuestions () {
    answerRes.queryAllQuestions(this.data.page,this.data.size)
      .then(res => {
       // 成功回调 
       console.log(res)
     }).catch(res => {
      // 失败回调
       console.log(res)
    })
  }
}))