微信小程式封裝get和post
阿新 • • 發佈:2019-01-05
最近開發小程式,根據小程式的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的使用方法都是一樣的。