hongjli
2025-06-05 d38a3ae95ce1ca3d736ec0f88f17973fa0d5a914
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const API_BASE_URL = 'http://121.43.139.99:8080/api';
 
interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
}
 
class ApiService {
  private static getToken(): string | null {
    if (typeof window !== 'undefined') {
      return localStorage.getItem('token');
    }
    return null;
  }
 
  static setToken(token: string): void {
    if (typeof window !== 'undefined') {
      localStorage.setItem('token', token);
    }
  }
 
  private static async fetchWithToken(url: string, options: RequestInit = {}, customToken?: string): Promise<ApiResponse> {
    const token = customToken || this.getToken();
    const headers = {
      'Content-Type': 'application/json',
      ...(token ? { 'token': token } : {}),
      ...options.headers,
    };
 
    const response = await fetch(`${API_BASE_URL}${url}`, {
      ...options,
      headers,
    });
 
    const data = await response.json();
    return data;
  }
 
  static async get<T>(url: string, customToken?: string): Promise<ApiResponse<T>> {
    return this.fetchWithToken(url, { method: 'GET' }, customToken);
  }
 
  static async post<T>(url: string, body: any, customToken?: string): Promise<ApiResponse<T>> {
    return this.fetchWithToken(url, {
      method: 'POST',
      body: JSON.stringify(body),
    }, customToken);
  }
 
  static async put<T>(url: string, body: any, customToken?: string): Promise<ApiResponse<T>> {
    return this.fetchWithToken(url, {
      method: 'PUT',
      body: JSON.stringify(body),
    }, customToken);
  }
 
  static async delete<T>(url: string, customToken?: string): Promise<ApiResponse<T>> {
    return this.fetchWithToken(url, { method: 'DELETE' }, customToken);
  }
}
 
export default ApiService;