Files
xingrin/frontend/lib/env.ts

38 lines
1.1 KiB
TypeScript
Raw Normal View History

2025-12-12 18:04:57 +08:00
/**
*
*/
const DEFAULT_DEV_BACKEND_URL = 'http://localhost:8888'
const stripTrailingSlash = (url: string) => url.replace(/\/+$/, '')
/**
* Next.js SSE
*/
export function getBackendBaseUrl(): string {
const envUrl = process.env.NEXT_PUBLIC_BACKEND_URL?.trim()
if (envUrl) {
return stripTrailingSlash(envUrl)
}
if (typeof window !== 'undefined') {
const origin = window.location.origin
// 本地开发时,默认后端运行在 8888 端口
if (window.location.hostname === 'localhost' && window.location.port === '3000') {
return stripTrailingSlash(DEFAULT_DEV_BACKEND_URL)
}
return stripTrailingSlash(origin)
}
return stripTrailingSlash(DEFAULT_DEV_BACKEND_URL)
}
/**
* API
*/
export function buildBackendUrl(path: string): string {
const base = getBackendBaseUrl()
const normalizedPath = path.startsWith('/') ? path : `/${path}`
return `${base}${normalizedPath}`
}