| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144 |
- // 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<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;
- // 处理认证失败
- const handleAuthError = () => {
- setToken(null);
- // 跳转到登录页
- router.push('/login');
- };
- // 基础请求方法
- export const request = async <T = any>(
- url: string,
- data: any = {},
- options: RequestOptions = {}
- ): Promise<ApiResponse<T>> => {
- const { method = 'POST' } = 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 (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 = <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 });
- };
|