微信小程序网络请求封装

/**
 * 基础网络请求封装
 */
const app = getApp();

function request(url, params = {}, method, loadingConfig, toastConfig) {
  // 默认不显示loading
  const { showLoading = false, loadingTitle = "加载中..." } = loadingConfig;
  // 默认显示toast
  const { showToast = true } = toastConfig;
  return new Promise((resolve, reject) => {
    if (showLoading) {
      wx.showLoading({ title: loadingTitle, icon: "none", mask: true });
    }
    const { domain, channel, userInfo, token, baseUrl } = app.globalData;
    const headerConfig = {
      "Content-Type": "application/json",
      "Channel": `${domain} ${channel}`
    };
    if (userInfo.user_id && token) {
      headerConfig["Authorization"] = `${userInfo.user_id} ${token}`;
    }
    wx.request({
      url: `${baseUrl}${url}`,
      data: params,
      method: method,
      header: headerConfig,

      success: res => {
        if (res.data.code != 0) {
          //请求结果失败
          // console.log(url, params, headerConfig);
          if (showToast) {
            wx.showToast({ title: res.data.message, icon: "none", duration: 2000 });
          }
          reject(res);
          return;
        }
        resolve(res.data.data);
      },
      fail: err => {
        wx.showToast({ title: "服务器请求失败,请稍后再试", icon: "none" });
        reject(err);
      },
      complete: () => {
        setTimeout(function () {
          wx.hideLoading();
        }, 2000);
      },
    });
  });
}

/**
 * get 网络请求
 */
function getRequest(url, params = {}, loadingConfig = {}, toastConfig = {}) {
  return request(url, params, "GET", loadingConfig, toastConfig);
}

/**
 * post 网络请求
 */
function postRequest(url, params = {}, loadingConfig = {}, toastConfig = {}) {
  return request(url, params, "POST", loadingConfig, toastConfig);
}

module.exports = {
  postRequest,
  getRequest
}

你可能感兴趣的:(微信小程序网络请求封装)