微信小程序接口封装

时间:2020-01-09
本文章向大家介绍微信小程序接口封装,主要包括微信小程序接口封装使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、创建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'
             })
       }
})

原文地址:https://www.cnblogs.com/jing-zhe/p/12172334.html