为了后期方便维护项目,对request进行一下封装,出于原生态微信小程序的特殊性,就不讲封装写在util.js中了,直接写在app.js中,那个页面用到就直接从getApp()中获取,更加方便。
首先,在app.js中进行wx.request的封装(目前这个项目,我是想获取数据时出现loading,结束后消除loading,所以加了complete里的函数):
baseUrl:'url',
request(params = {}){
//二次封装请求函数
return new Promise((resolve,reject)=>{
wx.showLoading({
title: '加载中...',
})
wx.request({
url: this.baseUrl + params.url,
method: params.method || 'GET',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: params.data || '',
success: (res) => {
resolve(res)
},
fail:(res) =>{
reject(err)
},
complete:(res) =>{
wx.hideLoading()
}
})
})
},
后面哪个页面需要用到request的时候,直接先引入request
const { request } = getApp()
接着正常请求任务
getList(){
request({
url:'/api/middle_show',
}).then(res=>{
console.log(res)
})
},
ps:封装过程中,为了以后少写点代码,所以默认为GET请求,只要后期不写method,那么默认一切为GET请求,data同理