wx.request

// 方式一
console.log('环境==', envVersion);
// const host = "https://springboot-hebq-84640-6-1323095709.sh.run.tcloudbase.com";
const host = "https://t.jiazhangq.cn";
const wxRequest = function (params, url) {
  console.log('wx=', params, url)
  wx.showToast({
    title: '加载中...',
    icon: 'loading'
  })
  wx.request({
    url: url,
    method: params.method || 'GET',
    data: params.data || {},
    header: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    },
    success: function (res) {
      params.success && params.success(res)
      wx.hideToast()
    },
    fail: function (res) {
      params.fail && params.fail(res)
    },
    complete: function (res) {
      params.complete && params.complete(res)
    }
  })
}

// 方式二
const wxRequest = async function (params, url) {
  wx.showToast({
    title: '加载中...',
    icon: 'loading'
  })
  const result = await new Promise((resolve, reject)=>{
    wx.request({
      url: url,
      method: params.method || 'GET',
      data: params.data || {},
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        wx.hideToast()
        resolve(res.data)
      },
      fail: function (res) {
        reject(res)
      },
      complete: function (res) {
        console.error(res);
      }
    });
  });
  return result
}

云托管

const wxCloud = async function (params, url, number = 0) {
  console.log('wxc=', params, url, number)
  const that = this
  let header = wx.getStorageSync('LoginInfo');
  
  console.log('header:', header)

  if(that.cloud == null){
    that.cloud = new wx.cloud.Cloud({
      identityless: true,
      resourceAppid: 'wx310de2a5ae44414f', // 微信云托管环境所属账号,服务商appid、公众号或小程序appid
      resourceEnv: 'prod-8gw8ynhq95367f2a', // 微信云托管的环境ID
    })
    await that.cloud.init({
      traceUser: true
    }) // init过程是异步的,需要等待init完成才可以发起调用
  }
  try{
    const result = await that.cloud.callContainer({
      path: url, // 填入业务自定义路径和参数,根目录,就是 / 
      method: params.method || 'GET', // 按照自己的业务开发,选择对应的方法
      header: header ? header : {},
      data: params.data || {}
    })
    console.log(`微信云托管调用结果${result.errMsg} | callid:${result.callID} `)
    // console.log(`接口请求调用结果:`+JSON.stringify(result))
    return result.data // 业务数据在data中
  } catch(e) {
    const error = e.toString()
     // 如果错误信息为未初始化,则等待300ms再次尝试,因为init过程是异步的
    if(error.indexOf("Cloud API isn't enabled") != -1 && number < 3){
      return new Promise((resolve)=>{
        setTimeout(() => {
          resolve(that.call(params, url, number + 1))
        }, 300)
      })
    } )
        }, 300)
      })
    } else {
      throw new Error(`微信云托管调用失败${error}`)
    }
  }
}
posted on 2024-01-14 20:31  羽丫头不乖  阅读(36)  评论(0编辑  收藏  举报