Files
device-voice-h5/utils/request.js
sexygoat cebe545440
All checks were successful
构建并部署前端到生产环境 / build-and-deploy (push) Successful in 48s
msg
2026-04-29 17:48:54 +08:00

58 lines
1.2 KiB
JavaScript

import { BASE_URL } from './env.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) {
uni.removeStorageSync('token');
uni.removeStorageSync('identifier');
showErrorToast(msg || '登录已过期,请重新登录');
setTimeout(() => {
uni.reLaunch({ url: '/pages/login/login' });
}, 2000);
reject(responseData);
return;
}
if (code === 0) {
resolve(data);
return;
}
if (options.showError !== false) {
showErrorToast(msg);
}
reject(responseData);
},
fail: (err) => {
showErrorToast('网络请求失败');
reject(err);
}
});
});
};
export default request;