微信小程序接口封装

一、创建utils/api.js

 

const host = ‘http://……‘

/**
 * 封装微信的request
 * form: ‘application/x-www-form-urlencoded‘
 */
function request(url, data = {}, method = "GET", contentType = ‘json‘) {
  return new Promise(function(resolve, reject) {
    wx.request({
      url: host+url,
      data: data,
      method: method,
      header: {
        ‘Content-Type‘: contentType.toLowerCase() == ‘json‘ ? "application/json" : "application/x-www-form-urlencoded"
      },
      success: function(res) {
        if (res.statusCode == 200) {
          resolve(res.data);
        } else {
          reject(res.errMsg);
        }
      },
      fail: function(err) {
        reject(err)
      }
    })
  });
}

module.exports = {
  request: request
}

二、引入

const api = require(‘../../utils/api.js‘)

三、使用

api.request(‘接口‘, {
              openId: App.globalData.openId,
              id: this.data.id
            }, "POST", ‘form‘).then(res => {
              if (res.code === 0) {
                wx.showToast({
                  title: ‘成功‘,
                  icon: ‘none‘
             })
       }
})

微信小程序接口封装

上一篇:微信公众号授权scope参数错误或没有scope权限


下一篇:java微信支付,对账单下载