最近开发小程序,根据小程序的API,我每发一次请求都要写一大串代码,而且都是重复的,所以我想封装一下,方便开发。
不多说直接贴代码:
首先我们先创建一个配置文件配置各种基础常量。
config.js
var config = {
APPID: 'your id',
BASE_URL:'your url',
}
//暴露接口
module.exports = config;
util.js
var config = require('config.js');//引入配置文件。
function Get(url,data,cb){
wx.showNavigationBarLoading();//顶部显示loading效果
wx.request({
url: config.BASE_URL + url,
data:data,
success:(res) => {
typeof cb == "function" && cb(res.data,"");
wx.hideNavigationBarLoading();//顶部隐藏loading效果
},
fail:(err) => {
typeof cb == "function" && cb(null,err.errMsg);
console.log("get 请求:" + config.BASE_URL);
console.log(err)
wx.hideNavigationBarLoading();
}
})
};
function Post(url, data, cb) {
wx.request({
method: 'POST',
url: config.BASE_URL + url,
data: data,
header:{
"Content-Type": "application/x-www-form-urlencoded"//跨域请求
},
success: (res) => {
typeof cb == "function" && cb(res.data, "");
},
fail: (err) => {
typeof cb == "function" && cb(null, err.errMsg);
console.log("post 请求:" + config.BASE_URL);
console.log(err);
}
});
};
//暴露接口
module.exports = {
httpGet: Get,
httpPost: Post
}
其中的cb作为一个回调函数,执行返回成功时的操作。至此我们成功封装了微信小程序的get和post两个方法。
比如在index.js使用如下:
var http = require('../../utils/util.js');
Page({
data: {
},
onLoad:function(){
http.httpGet("?action=index", {appid: config.APPID,}, function (res) {
console.log(res);
});
});
}
})
就像jquery的$.get(),post的使用方法都是一样的。