1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 微信小程序wx.request封装

微信小程序wx.request封装

时间:2021-04-23 23:00:29

相关推荐

微信小程序wx.request封装

实现功能:

1.实现对wx.request()的封装

2.使用封装后的wx.request()自动添加用户的openid和unionid

主要使用技术:promise

功能简述:

我们在使用微信小程序时为了区分用户通常会在请求头中填加用户的openid或unionid,通常做法是在app.js的onLaunch中写入获取openid的函数体。但是这样做有一个问题就是app.js中的onLaunch和页面的onload并没有严格的执行顺序。这就会造成又是发送请求时openid还未获取到。并且为了减少代码重复我想到的是封装wx.request().

话不多说贴代码

//此函数实现的是获取openidopenid(){wx.showLoading({title: '加载中',})return new Promise((resolve, reject)=>{let that=thiswx.login({timeout: 3000,success(res){if(res.code){wx.request({url: ‘填写你的获取openid的url’,method:"GET",success(res){resolve(res)},fail:function(e){reject(e)}})}}})})},//此函数实现的使用wx.request()发送请求after_request(params){return new Promise((resolve, reject)=>{wx.request({url: params.url,method:params.method||'GET',data:params.data||{},header:params.header,success(res){wx.hideLoading()resolve(res)},fail:function(e){reject(e)}})})},//此函数实现的是在发送网络请求前,查看本地是否含有openid和unionid,若存在则添加在请求头中,若不存在去执行openid()函数获取到openid后再去发送网络请求request(params){var that = thisif(params.method){params.method = params.method.toUpperCase()}if(that.globalData.openid!=''&&that.globalData.unionid!=''){if(params.header){params.header.openid = that.globalData.openidparams.header.unionid = that.globalData.unionid}else{params.header = {}params.header.openid = that.globalData.openidparams.header.unionid = that.globalData.unionid}var request = that.after_request(params)}else{var request = that.openid().then(res=>{if(params.header){params.header.openid = this.globalData.openidparams.header.unionid = this.globalData.unionid}else{params.header = {}params.header.openid = this.globalData.openidparams.header.unionid = this.globalData.unionid}return that.after_request(params)})}return request}})

其中openid()函数可以直接在onLaunch调用,然后执行一系列保存在本地的操作。

下面我们说如何使用封装后的wx.request()

在其他页面我们首先引入app.js

const app = getApp()//具体使用,我将在getData()函数中调用getData(){app.request({'url':你的api地址,'method':'GET'/'POST','data':你想发送的数据,可以不带此参数,'hedear':一些其余自定义请求头,默认openid和unionid}).then(res=>{console.log(res)//你想执行的操作})}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。