超好用超短的小程序请求封装
超好用超短的小程序请求封装
超好用超短的小程序请求封装,也不算特别特别短吧哈哈哈。但真的很好用的一个小程序请求封装,在请求的时候简短提高效率不需要将一样的东西重复写。下面就让大家看看这个封装是有多短,不够短的话也请别打我
网上多数使用的小程序封装是在单独的一个js文件,再使用module.exports进行输出方法。我所介绍的封装方法有异曲同工之妙,只不过是写在app.js里边,省去了使用时必须引用文件的麻烦。
app.js
xcxPost(options = {}) {
wx.showLoading({ mask: true, title: '', })
wx.request({
url: this.globalData.postUrl + options._url,
data: options._data || {},
method: "POST",
dataType: "json",
header: this.globalData.header,
success: (res) => {
if (res.data.errcode > 0) {
if (typeof options._success == "function") {
options._success(res.data);
}
} else {
this.xcxErrorToast({ title: res.data.errmsg || '服务器返回错误!' });
return;
}
},
fail: (res) => {
if (typeof options._fail == "function") {
options._fail(res);
}
if (typeof options._fail == "string") { //请求失败的弹框提示
wx.showToast({ title: options._fail, icon: 'loading', duration: 2000 });
}
},
complete: (res) => {
if (typeof options._complete == "function") {
options._complete(res);
}
wx.hideLoading()
}
});
},
此处的this.globalData,是在app.js设置的,也就是小程序的全局属性,不了解的朋友请查阅小程序官方文档
而以上封装具体的返回参数说明,请移步官方文档 https://developers.weixin.qq.com/miniprogram/dev/api/network-request.html#wxrequestobject
App({
globalData:{
userInfo:{},
postUrl: (wx.getExtConfigSync().request_url || '(后台接口地址)'),
header: {
'content-type': 'application/x-www-form-urlencoded',
'Cookie': ''
},
},
其他页面引用封装请求,比如 index.js
/**
* http请求
* 获得banner图
*/
getShopId(callBack) {
app.xcxPost({
_url:'pc_home_page/banner',// 你需要发起的请求;
_data: { type: '1' },// 你需要传的请求参数;
_success: (resp) => {//请求成功后的操作;if (resp.errcode > -1) {
// this.globalData.shopId = resp.list.shopId;
// this.globalData.domainUrl = resp.list.domain;
if (callBack) {
callBack()
}
}
}
})
},
原文出处:https://www.cnblogs.com/web1/archive/2018/07/23/9353410.html
分享文章如有侵权,版权等问题,请私信联系我,我将第一时间删除或修正。


浙公网安备 33010602011771号