api.js
1.04 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
// API基础地址
const API_BASE = import.meta.env.VITE_API_BASE || ''
let corpCode = ''
export function setCorpCode(value) {
corpCode = value ? String(value) : ''
}
export function getCorpCode() {
return corpCode
}
function isAbsoluteUrl(url) {
return /^https?:\/\//i.test(url)
}
// 生产环境后端路径不带 /api/ 前缀,这里做兼容处理
export function getApiUrl(url) {
if (!url) return API_BASE
if (isAbsoluteUrl(url)) return url
const cleanUrl = url.replace(/^\/api\//, '/')
return API_BASE + cleanUrl
}
export function withCorpCode(url) {
const fullUrl = getApiUrl(url)
if (!corpCode) return fullUrl
try {
const u = new URL(fullUrl, window.location.origin)
if (!u.searchParams.has('corpCode')) u.searchParams.append('corpCode', corpCode)
return u.toString()
} catch {
const sep = fullUrl.includes('?') ? '&' : '?'
return `${fullUrl}${sep}corpCode=${encodeURIComponent(corpCode)}`
}
}
export function apiFetch(url, options) {
return fetch(withCorpCode(url), options)
}
export default API_BASE