微信小程序網(wǎng)絡(luò)請(qǐng)求封裝

/**
 * 基礎(chǔ)網(wǎng)絡(luò)請(qǐng)求封裝
 */
const app = getApp();

function request(url, params = {}, method, loadingConfig, toastConfig) {
  // 默認(rèn)不顯示loading
  const { showLoading = false, loadingTitle = "加載中..." } = loadingConfig;
  // 默認(rèn)顯示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) {
          //請(qǐng)求結(jié)果失敗
          // 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: "服務(wù)器請(qǐng)求失敗,請(qǐng)稍后再試", icon: "none" });
        reject(err);
      },
      complete: () => {
        setTimeout(function () {
          wx.hideLoading();
        }, 2000);
      },
    });
  });
}

/**
 * get 網(wǎng)絡(luò)請(qǐng)求
 */
function getRequest(url, params = {}, loadingConfig = {}, toastConfig = {}) {
  return request(url, params, "GET", loadingConfig, toastConfig);
}

/**
 * post 網(wǎng)絡(luò)請(qǐng)求
 */
function postRequest(url, params = {}, loadingConfig = {}, toastConfig = {}) {
  return request(url, params, "POST", loadingConfig, toastConfig);
}

module.exports = {
  postRequest,
  getRequest
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容