zhangwencui
8 天以前 dab35bff798cfce2ddf7e8a67e4e1cdb144f5b4c
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
import { APP_COMPANY } from "../config/company";
 
// 后端地址跟随公司开关(src/config/company.ts 的 ACTIVE_COMPANY)一起切换
export const API_BASE_URL = APP_COMPANY.apiBaseUrl;
export const WEB_BASE_URL = APP_COMPANY.webBaseUrl;
 
export interface ApiResponse<T> {
  code: number;
  msg: string;
  data: T;
}
 
interface RequestOptions {
  data?: Record<string, unknown>;
  header?: Record<string, string>;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
}
 
export function request<T>(url: string, options: RequestOptions = {}) {
  return new Promise<T>((resolve, reject) => {
    uni.request({
      url: `${API_BASE_URL}${url}`,
      method: options.method ?? 'GET',
      data: options.data,
      header: {
        'content-type': 'application/json',
        ...options.header,
      },
      success: (response) => {
        const result = response.data as ApiResponse<T>;
        if (result?.code === 0) {
          resolve(result.data);
          return;
        }
        if (response.statusCode === 401 || result?.code === 401) {
          uni.$emit('auth-expired');
          reject(new Error('登录已过期,请重新登录'));
          return;
        }
        reject(new Error(result?.msg || '请求失败,请稍后重试'));
      },
      fail: () => reject(new Error('网络连接失败,请检查网络后重试')),
    });
  });
}