77 lines
2.2 KiB
JavaScript
77 lines
2.2 KiB
JavaScript
//const BASE_URL = 'https://muguaclub.cn';
|
|
//const BASE_URL = "http://127.0.0.1:8000";
|
|
const BASE_URL = 'https://m.muguaclub.cn/clock';
|
|
const STATIC_BASE_URL = 'https://m.muguaclub.cn';
|
|
|
|
let redirectingProfile = false;
|
|
|
|
function goProfile() {
|
|
if (redirectingProfile) {
|
|
return;
|
|
}
|
|
const pages = getCurrentPages();
|
|
const current = pages.length ? pages[pages.length - 1] : null;
|
|
const route = current && current.route;
|
|
if (route === 'pages/profile/profile') {
|
|
return;
|
|
}
|
|
redirectingProfile = true;
|
|
wx.switchTab({
|
|
url: '/pages/profile/profile',
|
|
complete() {
|
|
setTimeout(() => {
|
|
redirectingProfile = false;
|
|
}, 1200);
|
|
}
|
|
});
|
|
}
|
|
|
|
function request(options) {
|
|
const { url, method = 'GET', data = {}, auth = true } = options;
|
|
const isIdempotent = method === 'GET' || method === 'DELETE';
|
|
let retried = false;
|
|
|
|
return new Promise((resolve, reject) => {
|
|
const doRequest = () => {
|
|
const header = { 'Content-Type': 'application/json' };
|
|
const token = wx.getStorageSync('token');
|
|
if (auth && token) {
|
|
header['Authorization'] = 'Bearer ' + token;
|
|
}
|
|
wx.request({
|
|
url: BASE_URL + url,
|
|
method,
|
|
data,
|
|
header,
|
|
success(res) {
|
|
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
resolve(res.data);
|
|
} else if (res.statusCode === 401) {
|
|
wx.removeStorageSync('token');
|
|
if (auth) {
|
|
goProfile();
|
|
}
|
|
reject(res.data || { error: '未登录' });
|
|
} else {
|
|
reject(res.data || { error: '请求失败' });
|
|
}
|
|
},
|
|
fail(err) {
|
|
// 冷启动时首个请求可能因网络栈未就绪而失败,空闲时对幂等请求自动重试一次
|
|
const msg = (err && err.errMsg) || '';
|
|
const domainError = /url not in domain list|domain not/i.test(msg);
|
|
if (!retried && isIdempotent && !domainError) {
|
|
retried = true;
|
|
setTimeout(doRequest, 800);
|
|
return;
|
|
}
|
|
reject(err);
|
|
}
|
|
});
|
|
};
|
|
doRequest();
|
|
});
|
|
}
|
|
|
|
module.exports = { request, BASE_URL, STATIC_BASE_URL };
|