gov_propagandize/utils/http.js
itgaojian163 f9b148ca8a 初始化
2024-12-27 17:08:36 +08:00

86 lines
2.0 KiB
JavaScript

// 全局请求封装
const base_url = 'http://localhost:996';
export default (params) => {
let url = params.url;
let method = params.method || "GET";
let data = params.data || {};
let header = {};
if (method == "POST") {
header = {
'content-type': 'application/json'
};
}
// 获取本地token
const token = wx.getStorageSync("token");
if (token) {
header['Authorization'] = 'Bearer ' + token;
}
return new Promise((resolve, reject) => {
wx.request({
url: base_url + url,
method: method,
header: header,
data: data,
success(response) {
const res = response.data;
if (res.statusCode == 200) {
resolve(res);
} else {
wx.clearStorageSync();
switch (res.statusCode) {
case 401:
wx.showModal({
title: "提示",
content: "请登录",
showCancel: false,
success(res) {
setTimeout(() => {
wx.navigateTo({
url: "/pages/login/index",
});
}, 1000);
},
});
break;
case 404:
wx.showToast({
title: '请求地址不存在...',
duration: 2000,
});
break;
default:
wx.showToast({
title: '请重试...',
duration: 2000,
});
break;
}
}
},
fail(err) {
console.log(err);
if (err.errMsg.indexOf('request:fail') !== -1) {
wx.showToast({
title: '网络异常',
icon: "error",
duration: 2000
});
} else {
wx.showToast({
title: '未知异常',
duration: 2000
});
}
reject(err);
},
complete() {
wx.hideLoading();
wx.hideToast();
}
});
}).catch((e) => {});
};