/**
* 基础网络请求封装
*/
const app = getApp();
function request(url, params = {}, method, loadingConfig, toastConfig) {
// 默认不显示loading
const { showLoading = false, loadingTitle = "加载中..." } = loadingConfig;
// 默认显示toast
const { showToast = true } = toastConfig;
return new Promise((resolve, reject) => {
if (showLoading) {
wx.showLoading({ title: loadingTitle, icon: "none", mask: true });
}
const { domain, channel, userInfo, token, baseUrl } = app.globalData;
const headerConfig = {
"Content-Type": "application/json",
"Channel": `${domain} ${channel}`
};
if (userInfo.user_id && token) {
headerConfig["Authorization"] = `${userInfo.user_id} ${token}`;
}
wx.request({
url: `${baseUrl}${url}`,
data: params,
method: method,
header: headerConfig,
success: res => {
if (res.data.code != 0) {
//请求结果失败
// console.log(url, params, headerConfig);
if (showToast) {
wx.showToast({ title: res.data.message, icon: "none", duration: 2000 });
}
reject(res);
return;
}
resolve(res.data.data);
},
fail: err => {
wx.showToast({ title: "服务器请求失败,请稍后再试", icon: "none" });
reject(err);
},
complete: () => {
setTimeout(function () {
wx.hideLoading();
}, 2000);
},
});
});
}
/**
* get 网络请求
*/
function getRequest(url, params = {}, loadingConfig = {}, toastConfig = {}) {
return request(url, params, "GET", loadingConfig, toastConfig);
}
/**
* post 网络请求
*/
function postRequest(url, params = {}, loadingConfig = {}, toastConfig = {}) {
return request(url, params, "POST", loadingConfig, toastConfig);
}
module.exports = {
postRequest,
getRequest
}
微信小程序网络请求封装
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...