/** * HTTP请求封装 */ import { getToken } from './auth'; import { API_BASE_URL } from './config'; interface RequestOptions { url: string; method?: 'GET' | 'POST' | 'PUT' | 'DELETE'; data?: any; header?: Record; showLoading?: boolean; showError?: boolean; } interface Response { code: number; message: string; data: T; } /** * 发起HTTP请求 */ export function request(options: RequestOptions): Promise { const { url, method = 'GET', data, header = {}, showLoading = true, showError = true } = options; if (showLoading) { uni.showLoading({ title: '加载中...', mask: true }); } const token = getToken(); if (token) { header['adminAccessToken'] = token; } header['Content-Type'] = 'application/json'; return new Promise((resolve, reject) => { uni.request({ url: `${API_BASE_URL}${url}`, method, data, header, success: (res: any) => { if (showLoading) { uni.hideLoading(); } const response = res.data as Response; if (response.code === 200) { resolve(response.data); } else if (response.code === 401) { // Token过期,跳转登录 uni.removeStorageSync('admin_token'); uni.reLaunch({ url: '/pages/login/login' }); reject(new Error('登录已过期')); } else { if (showError) { uni.showToast({ title: response.message || '请求失败', icon: 'none' }); } reject(new Error(response.message)); } }, fail: (err) => { if (showLoading) { uni.hideLoading(); } if (showError) { uni.showToast({ title: '网络请求失败', icon: 'none' }); } reject(err); } }); }); } /** * GET请求 */ export function get(url: string, data?: any): Promise { return request({ url, method: 'GET', data }); } /** * POST请求 */ export function post(url: string, data?: any): Promise { return request({ url, method: 'POST', data }); } /** * PUT请求 */ export function put(url: string, data?: any): Promise { return request({ url, method: 'PUT', data }); } /** * DELETE请求 */ export function del(url: string, data?: any): Promise { return request({ url, method: 'DELETE', data }); }