// HTTP 请求封装 import { router } from 'expo-router'; import { COMMON_HEADER, SERVICE_URL } from './config'; export const SUCCESS_CODE = 0; export const AUTH_INVALID = 401; export const AUTH_INVALID_2 = 403; interface RequestOptions { loading?: boolean; showMsg?: boolean; method?: 'GET' | 'POST'; token?: string; } interface ApiResponse { code: number; msg: string; data: T; success: boolean; count?: number; } // 存储 token let authToken: string | null = null; export const setToken = (token: string | null) => { authToken = token; }; export const getToken = () => authToken; // 处理认证失败 const handleAuthError = () => { setToken(null); // 跳转到登录页 router.push('/login'); }; // 基础请求方法 export const request = async ( url: string, data: any = {}, options: RequestOptions = {} ): Promise> => { const { method = 'POST' } = options; const headers: Record = { 'Content-Type': 'application/json', track: JSON.stringify(COMMON_HEADER), }; if (authToken) { headers.Authentication = authToken; } const fullUrl = url.startsWith('http') ? url : `${SERVICE_URL}${url}`; try { const config: RequestInit = { method, headers, }; if (method === 'GET') { const params = new URLSearchParams(); Object.keys(data).forEach((key) => { if (data[key] !== undefined && data[key] !== null) { params.append(key, String(data[key])); } }); const queryString = params.toString(); const requestUrl = queryString ? `${fullUrl}?${queryString}` : fullUrl; const response = await fetch(requestUrl, config); const result = await response.json(); // 处理 401/403 认证失败 if (result.code === AUTH_INVALID || result.code === AUTH_INVALID_2) { handleAuthError(); return { code: result.code, msg: '登录已过期,请重新登录', data: null as any, success: false, }; } return { ...result, success: result.code == SUCCESS_CODE, // 使用 == 兼容字符串 "0" 和数字 0 }; } else { config.body = JSON.stringify(data); const response = await fetch(fullUrl, config); const result = await response.json(); // 处理 401/403 认证失败 if (result.code === AUTH_INVALID || result.code === AUTH_INVALID_2) { handleAuthError(); return { code: result.code, msg: '登录已过期,请重新登录', data: null as any, success: false, }; } return { ...result, success: result.code == SUCCESS_CODE, // 使用 == 兼容字符串 "0" 和数字 0 }; } } catch (error) { console.error('Request error:', error); return { code: -1, msg: '网络异常', data: null as any, success: false, }; } }; // GET 请求 export const get = (url: string, params: any = {}, options: RequestOptions = {}) => { return request(url, params, { ...options, method: 'GET' }); }; // POST 请求 export const post = (url: string, data: any = {}, options: RequestOptions = {}) => { return request(url, data, { ...options, method: 'POST' }); }; // 带 loading 的 GET 请求 export const getL = (url: string, params: any = {}, options: RequestOptions = {}) => { return get(url, params, { ...options, loading: true }); }; // 带 loading 的 POST 请求 export const postL = (url: string, data: any = {}, options: RequestOptions = {}) => { return post(url, data, { ...options, loading: true }); };