您的当前位置:首页正文

简单封装一下 微信的 wx.request

2024-11-26 来源:个人技术集锦
const apiRequest = (url, method, data, header) => {
  var promise = new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: header ? header : {},
      success: function (res) {
        if (res.statusCode === 200) {
          if (res.data) {
            if (res.data.ResultCode === "200") {
              resolve(stringToJson(res.data.ResultValue));
            }
            else {
              reject({ errormsg: '服务器错误,请稍后重试', code: res.data.ResultCode });
            }
          } else{
            reject({ errormsg: '服务器错误,请稍后重试', code: 0 });
          }
        } else{
          reject({ errormsg: '网络错误,请稍后重试', code: res.statusCode });
        }
      },
      fail: function (res) {
        // fail调用接口失败
        reject({ errormsg: '网络错误,请稍后重试', code: 0 });
      }
    })
  });
  return promise;
};

module.exports = {
  apiRequest: apiRequest
}

调用:

util.apiRequest(config.apiUrl + 'VCard/GetMyVCardList', 'POST', { UserID: 1218, PageIndex: 0, PageSize: that.data.PageSize })
      .then(function (data){
        that.setData({ PageIndex: 0, count: data.Count, vcardlist: data.VCardList });
        wx.hideNavigationBarLoading();//加载完毕隐藏加载动画
      },function(error){
        message.err(error.errormsg);
      })

显示全文