微信小程序封装get和post请求

143 阅读1分钟

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

/**
 * 请求相关的封装
 */
const apiUrl1 = 'URL1';
const apiUrl2 = "URL2"

let postHeader = {
  'content-type': 'application/x-www-form-urlencoded'
}
let getHeader = {
  'content-Type': 'application/json'
}

/**
 * 封装请求
 */
function fetch(options) {
  if (options.loading) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: options.url,
      data: options.data,
      header: options.method == "POST" ? postHeader : getHeader,
      method: options.method,
      success: function (res) {
        if (options.loading) {
          wx.hideLoading()
        }
        if (res.data.Code == 1) {
          // 重新登陆
          return false;
        }
        resolve(res); //把请求到的数据发到引用请求的地方
      },
      fail: function (err) {
        console.log(err)
        if (options.loading) {
          wx.hideLoading()
        }
        wx.showToast({
          title: "网络连接超时",
          icon: 'none',
          duration: 3000,
        })
      }
    })
  })
}
/**
 * POST 请求
 */
const post = function post(url, params, loading = true) {
  let option = {
    url: url,
    data: params,
    method: 'POST',
    loading
  }
  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: post,
  get: get,
  apiUrl1: apiUrl1,
  apiUrl2: apiUrl2
}

使用时,在需要发起请求的 js 文件引入

let http = require("../../utils/http")
使用时
      http.get(http.apiUrl1 + 'URL后面的', {
        	参数名:参数值
        }).then((res) => {
        	执行完成返回结果
      })
      http.post(http.apiUrl2 + 'URL后面的', {
        	参数名:参数值
        }).then((res) => {
        	执行完成返回结果
      })
若想取消请求时的 loading,在发起请求的参数后面加上false即可
      http.get(http.apiUrl1 + 'URL后面的', {
        	参数名:参数值
        },false).then((res) => {
        	执行完成返回结果
      })
      http.post(http.apiUrl2 + 'URL后面的', {
        	参数名:参数值
        },false).then((res) => {
        	执行完成返回结果
      })

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

Written ❤️ sywdebug.