在小程序开发中,通过接口获取后台数据,这时候我们不得不在每个页面的js文件中写到:wx.request({
url:'',.....}) 但是调用很多接口的时候,会非常频繁的使用request,作为一名php开发人员,显然我们需要对他进行一下封装:
1.在utils同级目录下建立service
2.typeof cb == "function" && cb(res.data) 我的理解是
利用的&&的运算规律,首先判断cb是不是一个方法, 这里的==可以作为类型是否相当的判断,然后在&&中如果前面的不满足,
后面的则不会执行;如果是cb是一个方法,调用cb方法,并且传入success成功回调的userinfo参数
并且return 的是回调函数,而不是具体的数据
var rootDocment = 'https://xxxxxxxxxxxxx/';
var header = {
'Accept': 'application/json',
'content-type': 'application/json',
'Authorization': null,
}
function getReq(url, cb) {
wx.showLoading({
title: '加载中',
})
console.log("header=="),
console.log(header)
wx.request({
url: rootDocment + url,
method: 'get',
header: header,
success: function (res) {
wx.hideLoading();
return typeof cb == "function" && cb(res.data)
},
fail: function () {
wx.hideLoading();
wx.showModal({
title: '网络错误',
content: '网络出错,请刷新重试',
showCancel: false
})
return typeof cb == "function" && cb(false)
}
})
}
function postReq(url, data, cb) {
wx.showLoading({
title: '加载中',
})
console.log("header=="),
console.log(header),
wx.request({
url: rootDocment + url,
header: header,
data: data,
method: 'post',
success: function (res) {
wx.hideLoading();
return typeof cb == "function" && cb(res.data)
},
fail: function () {
wx.hideLoading();
wx.showModal({
title: '网络错误',
content: '网络出错,请刷新重试',
showCancel: false
})
return typeof cb == "function" && cb(false)
}
})
}
module.exports = {
getReq: getReq,
postReq: postReq,
header: header,
}
header 中的一些数据可能是需要在app.js中登录后返回的Token,这时候我们需要在app.js中
var http = require('service/http.js')
http.header.Authorization = 'Bearer '+res.data;//给header 赋值
// 将方法暴露出去
getReq: http.getReq,
postReq: http.postReq,
使用:
http.getReq("item/getshopbanner/"+getApp().globalData.shopIdx,function(res){
console.log("banner==")
console.log(res)
})
微信小程序封装wx.request
发布:2021-06-03 10:39浏览: 次来源:网络 作者:tianshu
免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。
相关文章
- 微信小程序app.json文件常用配置说明2021-07-09
- 微信小程序文字控制单行超过显示省略号2021-07-09
- 微信小程序参数传递的几种方法2021-07-09
- 微信小程序使用button按钮分享2021-07-09
- 微信小程序的setData2021-07-09
- 小程序分享,获取openid2021-07-08
- 微信小程序-实现tab2021-07-08
- 微信开发者工具新建和导入小程序2021-07-08
- 微信小程序实现点击拍照长按录像功能2021-07-08
- 微信小程序必知知识2021-07-08