小程序Request的另类用法详解
前言
小程序中唯一能发送网络请求接口数据的是wx.request接口,当然这个接口存在诸多的限制,例如:10个并发请求限制,https限制(当然在开发阶段是可以关闭此限制),除了wx.request还有其他方法可以实现类型的功能吗?当然是有的,这个思路也源于我之前看到的一篇文章,随便笔记下来
思路
使用云开发来发送网络请求并把数据返回给小程序端。还不了解的云开发的同学请速度移步到官方【云开发】
新建一个http的云函数
//云函数入口文件
constcloud=require('wx-server-sdk')
constaxios=require('axios')
cloud.init()
//云函数入口函数
exports.main=async(event,context)=>{
constwxContext=cloud.getWXContext()
const{method,url,data}=event;
constres=awaitaxios.request({
method:method,
url:url,
data:data
});
return{code:1,data:res.data}||{code:-1,msg:'error',data:null}
}
小程序端二次封装云函数调用
asynchttp(options={}){
returnwx.cloud.callFunction({
name:'http',
data:{
method:options.method||'GET',
url:options.url||'',
data:options.data||{}
}
}).then(res=>{
returnres.result
})
},
小程序端使用
asynconLoad(){
this.http({
method:'GET',
url:'https://www.baidu.com'
}).then(res=>{
console.log(res)
})
},
总结
这种方法可以很好绕过https的限制,当然这只是提供一个简单的思路,我们可以进一步细一点封装,包括配置headerproxy等等功能,其实原理就是借助云函数做了二次转发,性能上肯定比不上原生的request
注意
async和await语法糖在最新的开发工具中已经实现了,开启增强编译即可使用,具体更新内容请移步官方社区微信小程序社区
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。