40 lines
807 B
JavaScript
40 lines
807 B
JavaScript
|
|
const API_BASE = String(import.meta.env.VITE_API_BASE_URL || '/api/v1').replace(/\/$/, '')
|
||
|
|
|
||
|
|
function buildUrl(path) {
|
||
|
|
if (!path.startsWith('/')) {
|
||
|
|
return `${API_BASE}/${path}`
|
||
|
|
}
|
||
|
|
|
||
|
|
return `${API_BASE}${path}`
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function apiRequest(path, options = {}) {
|
||
|
|
let response
|
||
|
|
|
||
|
|
try {
|
||
|
|
response = await fetch(buildUrl(path), {
|
||
|
|
headers: {
|
||
|
|
'Content-Type': 'application/json',
|
||
|
|
...(options.headers || {})
|
||
|
|
},
|
||
|
|
...options
|
||
|
|
})
|
||
|
|
} catch {
|
||
|
|
throw new Error('无法连接后端员工服务,请确认 FastAPI 已启动。')
|
||
|
|
}
|
||
|
|
|
||
|
|
let payload = null
|
||
|
|
|
||
|
|
try {
|
||
|
|
payload = await response.json()
|
||
|
|
} catch {
|
||
|
|
payload = null
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!response.ok) {
|
||
|
|
throw new Error(payload?.detail || '接口请求失败,请稍后重试。')
|
||
|
|
}
|
||
|
|
|
||
|
|
return payload
|
||
|
|
}
|