1. First add the following methods to the public app.js (or public JS file) :

App({
  // Post requests encapsulation
  post: function(url, data) {
    var promise = new Promise((resolve, reject) = > {
      var that = this
      var postData = data
      wx.request({
        url: url,
        data: postData,
        method: 'POST'.header: { 'content-type': 'application/x-www-form-urlencoded' },
        success: function(res) {
          // The server returns data
          if (res.data.ret === 'OK') {// Determine by the format of the data returned
            resolve(res)// Returns according to data format requirements
          } else {
            An error message is displayed
            reject(res.data.msg)
          }
        },
        fail: function(e) {
          reject('Network error')}})})return promise
  },
  / / get request
  get:function(url,data){
    var promise = new Promise((reslove,reject) = >{
      var that = this
      var getData = data 
      wx.request({
        url:url,
        data:getData,
        method:'GET'.header: {'content-type': 'application/x-www-form-urlencoded' },
        sucess:function(res){
          if (res.data.ret ==='OK') {
            reslove(res)
          } else {
            reject(res.data.msg)
          }
        },
        fail: {function(e){
            reject('Network error')}}})return promise
  }
})
Copy the code

2. Other pages call app.post()

const app = getApp();
Page({
  onLoad:function(){
      / / post request
      app.post(api,data)
      .then(res= > {
        console.log(res) // Return the result correctly
        wx.hideLoading()
      })
      .catch(errMsg= > {
        console.log(123) // Error message is displayed
        wx.hideLoading()
      })
}
})
Copy the code