68 lines
1.7 KiB
JavaScript
68 lines
1.7 KiB
JavaScript
import { BASE_URL } from './env.js';
|
|
import { useUserStore } from '@/store/user.js';
|
|
|
|
const showErrorToast = (message) => {
|
|
uni.showToast({
|
|
title: message || '请求失败,请稍后重试',
|
|
icon: 'none',
|
|
duration: 2000
|
|
});
|
|
};
|
|
|
|
const request = (options) => {
|
|
return new Promise((resolve, reject) => {
|
|
const token = uni.getStorageSync('token') || '';
|
|
|
|
uni.request({
|
|
url: BASE_URL + options.url,
|
|
method: options.method || 'GET',
|
|
data: options.data || {},
|
|
header: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': token ? `Bearer ${token}` : '',
|
|
...options.header
|
|
},
|
|
success: (res) => {
|
|
const responseData = res.data || {};
|
|
const { code, msg, data } = responseData;
|
|
|
|
if (res.statusCode === 401) {
|
|
// A late response from an old login must not clear a new session.
|
|
if (token === (uni.getStorageSync('token') || '')) {
|
|
useUserStore().clearUser();
|
|
showErrorToast(msg || responseData.message || '登录已过期,请重新登录');
|
|
setTimeout(() => {
|
|
if (!uni.getStorageSync('token')) uni.reLaunch({ url: '/pages/login/login' });
|
|
}, 2000);
|
|
}
|
|
reject(responseData);
|
|
return;
|
|
}
|
|
|
|
if (code === 0) {
|
|
resolve(data);
|
|
return;
|
|
}
|
|
|
|
if (options.showError !== false) {
|
|
showErrorToast(msg || responseData.message);
|
|
}
|
|
reject(responseData);
|
|
},
|
|
fail: (err) => {
|
|
if (options.showError !== false) {
|
|
showErrorToast('网络请求失败');
|
|
}
|
|
// A transport failure does not tell us whether the backend created a
|
|
// payment. Callers must reconcile status and must not retry creation.
|
|
reject({
|
|
...err,
|
|
paymentResultUnknown: true
|
|
});
|
|
}
|
|
});
|
|
});
|
|
};
|
|
|
|
export default request;
|