35 lines
1.2 KiB
TypeScript
35 lines
1.2 KiB
TypeScript
import { defineEventHandler, getHeader, getRequestURL, getRouterParam, proxyRequest, getCookie } from 'h3'
|
|
import { useRuntimeConfig } from '#imports'
|
|
|
|
function joinURL(base: string, path: string) {
|
|
if (!path) return base
|
|
return base.replace(/\/+$/, '') + '/' + path.replace(/^\/+/, '')
|
|
}
|
|
|
|
export default defineEventHandler((event) => {
|
|
const config = useRuntimeConfig()
|
|
|
|
// 从 Cookie 读取环境设置,优先于环境变量
|
|
const envCookie = getCookie(event, 'websopy_api_env')
|
|
const isDevEnv = envCookie === 'dev'
|
|
|
|
// 开发环境使用本地 9500 端口,生产环境使用配置的环境变量
|
|
const serverApiBase = isDevEnv
|
|
? 'https://server.websoft.top/api'
|
|
: (config.public.serverApiBase || config.public.ServerApi || 'https://server.websoft.top/api')
|
|
|
|
const path = getRouterParam(event, 'path') || ''
|
|
const search = getRequestURL(event).search
|
|
const target = joinURL(serverApiBase, path) + search
|
|
|
|
const tenantId = getHeader(event, 'tenantid') || config.public.tenantId
|
|
const authorization = getHeader(event, 'authorization')
|
|
|
|
return proxyRequest(event, target, {
|
|
headers: {
|
|
TenantId: String(tenantId),
|
|
...(authorization ? { Authorization: String(authorization) } : {})
|
|
}
|
|
})
|
|
})
|