backend-resolver.ts
2.57 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
* @Author: liimin 17653212@qq.com
* @Date: 2026-10-12 10:21:57
* @LastEditors: liimin 17653212@qq.com
* @LastEditTime: 2026-10-12 11:48:50
* @FilePath: \uj-store\src\api\core\backend-resolver.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
// 浏览器侧:根据「当前访问地址」动态解析后端服务地址。
const HOST_BACKEND_MAP: Record<string, string> = {
'192.168.1.237': '192.168.3.197:8788', // 省略协议 → 访问 http 拼 http、访问 https 拼 https
// 'localhost:5173': '192.168.3.197:8788',
// 'x.dev.cn': 'http://192.168.3.197:8788', // 写全协议则不跟随,固定 http
};
function stripTrailingSlash(url: string): string {
return url.replace(/\/+$/, '');
}
/** 当前页面协议('http:' / 'https:');非浏览器环境回退 https。 */
function currentProtocol(): string {
if (typeof window !== 'undefined' && window.location) return window.location.protocol;
return 'https:';
}
/**
* 给映射值补协议,兼容 http / https:
* - 已含协议(http:// / https://)→ 原样返回;
* - 协议相对(//host)→ 跟随当前页协议;
* - 仅 host(youjia-api.xxx.com / host:port / host/path)→ 跟随当前页协议补上。
* 这样映射表不必写死协议,http 访问解析到 http 后端、https 访问解析到 https 后端。
*/
function withProtocol(raw: string): string {
const v = raw.trim();
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(v)) return v;
if (v.startsWith('//')) return currentProtocol() + v;
return currentProtocol() + '//' + v;
}
/**
* 解析 direct 模式下的后端 origin。
* 仅在浏览器侧调用(config.ts 加载期),Node 侧不会走到此函数。
*/
export function resolveBackendOrigin(): string {
const envTarget = stripTrailingSlash(
String((import.meta.env as Record<string, string | undefined>).VITE_API_TARGET ?? '').trim(),
);
if (typeof window === 'undefined' || !window.location) return envTarget;
const host = window.location.host; // 含端口
const hostNoPort = host.split(':')[0];
const mapped = HOST_BACKEND_MAP[host] ?? HOST_BACKEND_MAP[hostNoPort];
if (mapped) return stripTrailingSlash(withProtocol(mapped));
// 默认同源:访问地址即后端地址(youjia.dev.glsx.com.cn → 后端 youjia.dev.glsx.com.cn)
const origin = window.location.origin;
if (origin && origin !== 'null' && !origin.startsWith('file:')) return origin;
// 极端兜底:非浏览器 / origin 不可用
return envTarget;
}