微信小程序封装一个简单的请求
最近因为项目需要,自己也要写小程序了。看到别人写的代码很简洁,看看自己频繁的写wx.request()
,于是就想封装一个自己使用的请求。
新建一个文件夹
util
在这个文件夹里面新建一个文件
httputil.js
编写这个文件
//控制loading是因为有时一个页面会请求多个接口,出现多个loading体验不是很好
function get(url, params, onSuccess, loadding = true){
request(url, params, "GET", onSuccess, loadding);
}
function post(url, params, onSuccess, loadding = true){
request(url, params, "POST", onSuccess, loadding);
}
function request(url, params = {}, method = 'GET', onSuccess, loadding = true) {
if (loadding==true) {
wx.showLoading({
title: "加载中...",
})
};
wx.request({
url: get_url(url),
data: params,
method: method,
header: {
'content-type': 'application/json',
'token' : wx.getStorageSync('token')
},
success: function(res) {
if (loadding==true) {
wx.hideLoading();
}
if (res.data) {
if (res.statusCode == 200) {
onSuccess(res.data);
} else {
console.log(res);
wx.showToast({
title: '请求失败',
icon: 'none',
duration: 3000
});
}
}
},
fail: function(error) {
console.log(error);
wx.showToast({
title: error.errMsg,
icon: 'none',
duration: 3000
});
}
})
}
function get_url(url) {
var base_url = "https://www.huangzhongxin.cn/";
return base_url + url;
}
//提供给外部使用
module.exports = {
post: post,
get: get,
}
外部调用
//引入
var http = require('../../util/httputil.js');
http.get('api/Index/index', {}, function(res){
console.log(res);
}, true);
http.post('api/Index/index', {}, function(res){
console.log(res);
}, true);