数据交互之封装request请求(微信小程序篇)

在前后端数据交互中,数据请求是一个很重要的环节,request请求也是出现在交互中的重点,进行请求方式的封装是为了减轻数据请求的体量,最大化进行代码的复用,也是面向对象编程的基础思想。

//这个是一个小程序的全局变量设置,其中的url地址是在app.js中的 globalData设置中取出。

var AppLestUrl = getApp().globalData.wxurl;

//简单的函数封装
/url:表示请求地址,
header:表示请求头数据组,
cd:表示请求返回函数
sc:表示请求返回的编码,(可根据后台返回编码的复杂程度来改变)
/
//GET请求方式
function getReq(url,header,cb,sc) {
//加载动画
wx.showLoading({
title: '加载中',
})
console.log(header);
wx.request({
url: AppLestUrl + url,
method: 'GET',
header: header,
//正确请求流程
success: function (res) {
wx.hideLoading();
console.log(res);
var JsonData = res.data;
var JsonCode = res.statusCode;
return typeof cb == "function" && cb(JsonData, JsonCode);
},
//异常请求流程
fail: function () {
wx.hideLoading();
wx.showModal({
title: '网络错误',
content: '网络出错,请刷新重试',
showCancel: false
})
return typeof cb == "function" && cb(false)
}
})
}
//POST请求方式
/*data:表示的是上传数据体*/
function postReq(url, data, header,cb) {
wx.showLoading({
title: '提交中',
})
console.log(header),
wx.request({
url: AppLestUrl + url,
header: header,
data: data,
method: 'POST',
success: function (res) {
wx.hideLoading();
var JsonData = res.data;
console.log(JsonData);
var JsonCode = res.statusCode;
return typeof cb == "function" && cb(JsonData, JsonCode)
},
fail: function () {
wx.hideLoading();
wx.showModal({
title: '网络错误',
content: '网络出错,请刷新重试',
showCancel: false
})
return typeof cb == "function" && cb(false)
}
})

}
微信小程序里面request请求不像JavaScript里面的数据请求,在小程序里面必须要进行方法暴露,才可以在其他的js文件里面请求到先前封装的方法。

在公共文件里面暴露封装方法

module.exports = {
getReq: getReq,
postReq: postReq,
}
对于公共方法js的调用,里面的http.js就是你公共方法的js

var HttpRequest = require("../../http.js"); //HTTP请求request封装 调用

getReq: HttpRequest.getReq,//GET数据请求函数
postReq: HttpRequest.postReq,//POST数据请求

//GET请求
HttpRequest.getReq(infoUrl, headmode, function (res,code) {
console.log(res);
})
//POST请求
HttpRequest.postReq(url, JsonData, headers,function (res,code) {
console.log(res);
})

转载于:https://www.cnblogs.com/Victory-peng/articles/9355280.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值