小程序的API封装

首先在utils文件夹在创建api.js文件,代码如下:


 const API_URL = 'http://192.168.0.31:808/ppapi/' //本地api地址,当然你也可以定义在全局(APP.js),看个人喜好吧
module.exports = {
  _orginMethod: function (method, url, data, header) {
    let obj = {};
    if (!method) return console.error('method is necessary in this function');
    if (typeof method != 'string') return console.error('method is incorrect type');
    method = method.toLocaleUpperCase()
    if (method != 'GET' && method != 'POST' && method != 'PUT') return console.error('method is inexistence');
    if (header) obj.header = header;
    return new Promise((resolve, reject) => {
      wx.request(Object.assign({}, {
        url: API_URL + url,
        method: method,
        data: data,
        success: (res) => {
          if (res.data.code == 1 || res.data.code == 0) {
            resolve(res)
          } else {
            console.warn(`data problem in api ${this._host}${url}`, res)
            reject(res)
          }
        },
        fail: (res) => {
          console.error(`data problem in api ${this._host}${url}`, res)
          reject(res)
        }
      }, obj))
    })
  },
  // header为token,剩下的请求方法跟下面的差不多的。
  Get: function (url, data, header) {

return this._orginMethod('GET', url, data, header)

  },
  Post: function (url, data, header) {
    return this._orginMethod('POST', url, data, header)
  },
  Put: function (url, data, header) {
    return this._orginMethod('PUT', url, data, header)
  },
  
}

api的使用:

app.js

const API_URL = require('/utils/api.js')
App({
  apiModule: API_URL,//api模块,
}

需要使用api的文件:index.js

var appAPI = getApp(); // 取得全局App
getExamList(){
   let token= wx.getStorageSync('token')
    appAPI.apiModule.Get('exam/accomplish/examination', {
      参数1,参数2,参数3...
    }, { token }).then(res => {
      if (res.data.code == 0) {
       //请求成功
      }
    }).catch(err => {
    //异常捕获
    })
}

你可能感兴趣的:(小程序)