关注我的简书,有很好的文章分享给您(https://www.jianshu.com/u/d90be3fdd9c5)

数据交互之封装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);
})

posted @ 2018-07-23 16:20  鹏帅  阅读(452)  评论(0编辑  收藏  举报

关注我的简书,有很好的文章分享给您(https://www.jianshu.com/u/d90be3fdd9c5)