微信小程序封装get和post

首先我们先创建一个配置文件配置各种基础常量。

config.js

1
2
3
4
5
6
var config = {
APPID: 'your id',
BASE_URL:'your url',
}
//暴露接口
module.exports = config;

util.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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使用如下:

1
2
3
4
5
6
7
8
9
10
11
var http = require('../../utils/util.js');
Page({
data: {
},
onLoad:function(){
http.httpGet("?action=index", {appid: config.APPID,}, function (res) {
console.log(res);
});
});
}
})