32 lines
834 B
TypeScript
32 lines
834 B
TypeScript
// frontend/src/lib/api.ts
|
|
|
|
// ✅ DEV: immer relativ, damit Vite-Proxy (/api -> :9999) greift → kein CORS
|
|
// ✅ PROD: optional per VITE_API_BASE überschreiben
|
|
const API_BASE =
|
|
import.meta.env.VITE_API_BASE ??
|
|
(import.meta.env.DEV ? '' : '')
|
|
|
|
export const apiUrl = (path: string) => {
|
|
const p = path.startsWith('/') ? path : `/${path}`
|
|
return `${API_BASE}${p}`
|
|
}
|
|
|
|
export async function apiFetch(path: string, init?: RequestInit) {
|
|
const res = await fetch(apiUrl(path), {
|
|
...init,
|
|
credentials: 'include',
|
|
headers: {
|
|
...(init?.headers ?? {}),
|
|
'Content-Type': (init?.headers as any)?.['Content-Type'] ?? 'application/json',
|
|
},
|
|
})
|
|
|
|
if (res.status === 401) {
|
|
// optional: SPA route
|
|
if (!location.pathname.startsWith('/login')) {
|
|
location.href = '/login'
|
|
}
|
|
}
|
|
return res
|
|
}
|