import { BASE_URL, REQUEST_TIMEOUT } from './config.js' import store from './store.js' let redirecting = false /** * 统一请求封装 * - 自动携带 token * - code=1 视为成功,直接返回 data * - 401 清理登录态并跳转登录页 * - 其它错误统一 toast,返回 rejected Promise 供页面自行处理 */ export function request(path, options = {}) { const { method = 'GET', data = {}, auth = true, silent = false, loading = false } = options return new Promise((resolve, reject) => { if (loading) { uni.showLoading({ title: '加载中', mask: true }) } const header = { 'Content-Type': 'application/x-www-form-urlencoded' } if (auth && store.token) { header.token = store.token } uni.request({ url: BASE_URL + path, method, data, header, timeout: REQUEST_TIMEOUT, success: (res) => { const body = res.data || {} // FastAdmin 业务错误 if (body.code === 1) { resolve(body.data || {}) return } if (res.statusCode === 401 || body.code === 401) { handleUnauthorized() reject(body) return } if (!silent) { uni.showToast({ title: body.msg || '请求失败', icon: 'none' }) } reject(body) }, fail: (err) => { if (!silent) { uni.showToast({ title: '网络异常,请稍后重试', icon: 'none' }) } reject(err) }, complete: () => { if (loading) { uni.hideLoading() } } }) }) } function handleUnauthorized() { if (redirecting) return redirecting = true store.clear() uni.showToast({ title: '登录已过期,请重新登录', icon: 'none' }) setTimeout(() => { uni.reLaunch({ url: '/pages/login/index' }) redirecting = false }, 600) } export default request