当前位置:   article > 正文

微信小程序封装 get 和 post 请求_微信开发者全局封装get和post请求

微信开发者全局封装get和post请求

在 util 里面新建 http.js 文件,写入以下内容

const apiUrl = "https://xl.qdscitech.net"

function showLoading() {
  wx.showLoading({
    title: '加载中',
    mask: true
  });
}

function hideLoading() {
  wx.hideLoading();
}

function showErrorToast(message) {
  wx.showToast({
    title: message,
    icon: 'none',
    duration: 3000
  });
}
/**
 * 封装请求
 */
function fetch(options) {
  if (options.loading) {
    showLoading();
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: apiUrl + options.url,
      data: options.data,
      header: {
        "Content-Type": options.contentType
      },
      method: options.method,
      success: function (res) {
        if (options.loading) {
          hideLoading();
        }
        if (res.statusCode !== 200) {
          showErrorToast("请求失败");
          return reject(new Error("Request failed"));
        }
        if (res.data.code !== 1) {
          showErrorToast(res.data.msg);
          return reject(new Error(res.data.msg));
        }
        resolve(res.data); //把请求到的数据发到引用请求的地方
      },
      fail: function (err) {
        if (options.loading) {
          wx.hideLoading()
        }
        showErrorToast("网络连接超时");
        reject(err);
      }
    })
  })
}
/**
 * POST 请求
 */
const post = function post(url, params, loading = true, contentType = "application/json") {
  let option = {
    url: url,
    data: params,
    method: 'POST',
    loading,
    contentType
  }
  return fetch(option);
}

/**
 * GET请求
 */
const get = function get(url, params, loading = true) {
  let option = {
    url: url,
    data: params,
    method: 'GET',
    loading
  }
  return fetch(option);
}
module.exports = {
  post,
  get,
  apiUrl,
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90

❀❀❀❀❀❀ 完结散花 ❀❀❀❀❀❀

Written ❤️ sywdebug.
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/597804
推荐阅读
  

闽ICP备14008679号