封装微信小程序请求

/**
 * 封装wx:request请求的工具
 */
const baseUrl = "";
const https = ({ url = '', param = {}, ...other } = {}) => {
    wx.showLoading({
      title: '请稍等...'
    });
    return new Promise((resolve, reject) => {
      wx.request({
        url:getUrl(url),
        data: param,
        header: {
          'content-type': 'application/json'
        },
        ...other,
        success: (res) => {
            wx.hideLoading();
            resolve(res)
        },
        fail:(res)=>{
            wx.hideLoading();
            wx.showModal({
              content: '请求超时!请检查当前网络!',
              showCancel: false,
              success(res) { }
            })
            reject(res)
        }
      })
    })
}
//判断传递过来的请求路径是否是完整的url地址
const getUrl = (url) => {
  if (!url.includes('://')) {
      url = baseUrl + url;
    }
    return url
}
//封装get请求
const httpGet = (url, param = {}) => {
    return https({
      url,
      method:'GET',
      param
    })
}
//封装post请求
const httpPost = (url, param = {}) => {
    return https({
      url,
      method:'POST',
      param
    })
}
export default{
  httpGet,
  httpPost
}

 

 

你可能感兴趣的:(微信小程序,数据请求)