微信小程序云开发request请求封装

1、app.js中代码封装

// app.js
App({
    async onLaunch() {
      // 这里演示如何在 app.js 中使用,没有用请删掉
      // const res = await this.call({
      //   path:'/',
      //   method: 'POST'
      // })
      // console.log('业务返回结果',res)
    },
    /**
     * 封装的微信云托管调用方法
     * @param {*} obj 业务请求信息,可按照需要扩展
     * @param {*} number 请求等待,默认不用传,用于初始化等待
     */
    async call(obj, number=0){
      const that = this
      if(that.cloud == null){
        that.cloud = new wx.cloud.Cloud({
          resourceAppid: 'xxx', // 微信云托管环境所属账号,服务商appid、公众号或小程序appid
          resourceEnv: 'xxx', // 微信云托管的环境ID
        })
        await that.cloud.init() // init过程是异步的,需要等待 init 完成才可以发起调用
      }
      try{
        const result = await that.cloud.callContainer({
          path: obj.path, // 填入业务自定义路径和参数,根目录,就是 / 
          method: obj.method||'GET', // 按照自己的业务开发,选择对应的方法
          // dataType:'text', // 如果返回的不是 json 格式,需要添加此项
          header: {
            'X-WX-SERVICE': 'springboot-nhvu', // xxx中填入服务名称(微信云托管 - 服务管理 - 服务列表 - 服务名称)
            // 其他 header 参数
          },
          // 其余参数同 wx.request
          data:obj.data || {}
          
        })
        console.log(`微信云托管调用结果${result.errMsg} | callid:${result.callID}`)
        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(function(){
              resolve(that.call(obj,number+1))
            },300)
          })
        } else {
          throw new Error(`微信云托管调用失败${error}`)
        }
      }
    }
  })

注意:参数传递data:obj.data || {} 与wx.request一样

2、在需要的页面的index.js中引入 app.js

// 例如在 page/index/index.js
const app = getApp()

3、调用方式

async onLoad(options){
      // 调用方式
      await app.call({
            path:'/api/xx/xx'
      })
},

总结: 按照以上几步,即可完成微信小程序云开发的rquest 请求封装及调用!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值