| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196 |
- // HTTP 请求封装
- import { router } from 'expo-router';
- import { Alert, Platform } from 'react-native';
- import { COMMON_HEADER, SERVICE_URL } from './config';
- export const SUCCESS_CODE = 0;
- export const SUCCESS_CODE_200 = 200;
- export const AUTH_INVALID = 401;
- export const AUTH_INVALID_2 = 403;
- interface RequestOptions {
- loading?: boolean;
- showMsg?: boolean;
- method?: 'GET' | 'POST';
- token?: string;
- silent?: boolean; // 静默模式,不显示错误提示
- }
- interface ApiResponse<T = any> {
- 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;
- export const clearToken = async () => {
- authToken = null;
- };
- // 处理认证失败
- const handleAuthError = () => {
- setToken(null);
- // 跳转到登录页
- router.push('/login');
- };
- // 检查是否认证失败
- const isAuthError = (code: number | string) => {
- const numCode = Number(code);
- return numCode === AUTH_INVALID || numCode === AUTH_INVALID_2;
- };
- // 检查是否成功的 code
- const isSuccessCode = (code: number | string) => {
- const numCode = Number(code);
- return numCode === SUCCESS_CODE || numCode === SUCCESS_CODE_200;
- };
- // 显示错误提示(兼容 Web 和 Native)
- const showErrorMessage = (msg: string) => {
- const message = msg || '请求失败,请稍后重试';
- if (Platform.OS === 'web') {
- // Web 环境使用 window.alert
- window.alert(message);
- } else {
- // Native 环境使用 Alert.alert
- Alert.alert('提示', message);
- }
- };
- // 基础请求方法
- export const request = async <T = any>(
- url: string,
- data: any = {},
- options: RequestOptions = {}
- ): Promise<ApiResponse<T>> => {
- const { method = 'POST', silent = false } = options;
- const headers: Record<string, string> = {
- '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 (isAuthError(result.code)) {
- handleAuthError();
- return {
- code: result.code,
- msg: '登录已过期,请重新登录',
- data: null as any,
- success: false,
- };
- }
- const success = isSuccessCode(result.code);
-
- // 非成功状态且非静默模式,显示错误提示
- if (!success && !silent && result.msg) {
- showErrorMessage(result.msg);
- }
-
- return {
- ...result,
- success,
- };
- } else {
- config.body = JSON.stringify(data);
- const response = await fetch(fullUrl, config);
- const result = await response.json();
-
- // 打印接口返回内容
- console.log('[HTTP Response]', fullUrl, result);
-
- // 处理 401/403 认证失败(不显示错误提示,直接跳转登录)
- if (isAuthError(result.code)) {
- handleAuthError();
- return {
- code: result.code,
- msg: '登录已过期,请重新登录',
- data: null as any,
- success: false,
- };
- }
- const success = isSuccessCode(result.code);
-
- // 非成功状态且非静默模式,显示错误提示
- if (!success && !silent && result.msg) {
- console.log('[HTTP Error]', fullUrl, 'msg:', result.msg, 'silent:', silent);
- showErrorMessage(result.msg);
- }
-
- return {
- ...result,
- success,
- };
- }
- } catch (error) {
- console.error('Request error:', error);
- if (!silent) {
- showErrorMessage('网络异常,请检查网络连接');
- }
- return {
- code: -1,
- msg: '网络异常',
- data: null as any,
- success: false,
- };
- }
- };
- // GET 请求
- export const get = <T = any>(url: string, params: any = {}, options: RequestOptions = {}) => {
- return request<T>(url, params, { ...options, method: 'GET' });
- };
- // POST 请求
- export const post = <T = any>(url: string, data: any = {}, options: RequestOptions = {}) => {
- return request<T>(url, data, { ...options, method: 'POST' });
- };
- // 带 loading 的 GET 请求
- export const getL = <T = any>(url: string, params: any = {}, options: RequestOptions = {}) => {
- return get<T>(url, params, { ...options, loading: true });
- };
- // 带 loading 的 POST 请求
- export const postL = <T = any>(url: string, data: any = {}, options: RequestOptions = {}) => {
- return post<T>(url, data, { ...options, loading: true });
- };
|