api-mode.ts
2 KB
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
// 前端接后端的两种模式,由单一开关 VITE_API_MODE 决定。
//
// 本模块被【两侧共同 import】:
// Node 侧 vite.config.ts —— 决定是否挂 server.proxy、代理 target 是多少
// 浏览器侧 src/api/core/config.ts —— axios baseURL 是多少
// 这样「代理是否启用」与「baseURL 是什么」由同一段逻辑推导,
// 从根上杜绝「开着代理却打直连」或「关了代理却还在打 /api」这类错配。
//
// 不要在本文件里使用 import.meta.env / window / document 等浏览器 API,
// Node 侧(Vite 配置加载)也必须能 import 它。env 由调用方作为参数传入。
export type ApiMode = 'proxy' | 'direct';
export interface ApiModeConfig {
/** proxy=走 Vite 代理(同源,浏览器不跨域);direct=浏览器直连后端(需后端开放 CORS) */
mode: ApiMode;
useProxy: boolean;
/** 后端真实地址。direct 模式下它就是 baseURL;proxy 模式下它是代理 target */
target: string;
/** axios baseURL:proxy → '/api';direct → 后端完整地址(无 /api 前缀) */
baseURL: string;
}
/**
* 由环境变量推导当前接法。
* VITE_API_MODE 只有两个取值:proxy(默认)/ direct,其余值一律按 proxy 处理。
*/
export function resolveApiMode(env: Record<string, string | undefined>): ApiModeConfig {
const raw = String(env.VITE_API_MODE ?? 'proxy')
.trim()
.toLowerCase();
const useProxy = raw !== 'direct';
// 后端地址唯一来源是 .env 的 VITE_API_TARGET;未配置则为空(属配置缺失,需由 .env 补齐)。
const target = String(env.VITE_API_TARGET ?? '')
.trim()
.replace(/\/+$/, '');
return {
mode: useProxy ? 'proxy' : 'direct',
useProxy,
target,
// /api 前缀是给代理用的识别标记,后端没有这个 context-path;
// 把它带给后端会让 request.getRequestURI() 与前端签名的 /system/auth/login 不一致 → 10011。
baseURL: useProxy ? '/api' : target,
};
}