diff --git a/docs/development-standards.md b/docs/development-standards.md index f71759e..97f88e2 100644 --- a/docs/development-standards.md +++ b/docs/development-standards.md @@ -345,8 +345,11 @@ const router = createBrowserRouter(routes, { **api.ts 中的 base URL 自动拼接:** ```typescript -const APP_BASE_URL = '/app_03'; // 由环境变量 VITE_APP_BASE_URL 控制 -function joinPath(prefix: string, path: string) { +const API_PREFIX = import.meta.env.VITE_API_PREFIX || "/api"; +// APP_BASE_URL = basename = 从 API_PREFIX 提取("/app_03/api" → "/app_03") +const APP_BASE_URL = API_PREFIX.replace(/\/api\/?$/, '') || '/'; + +function joinPrefix(prefix: string, path: string) { const p = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix; const s = path.startsWith('/') ? path : `/${path}`; return `${p}${s}`; @@ -354,6 +357,26 @@ function joinPath(prefix: string, path: string) { // 最终请求: /app_03/api/xxx ``` +**.env 配置:** +```ini +# API_PREFIX 必须带 basename,开发和 Nginx 代理一致 +VITE_API_PREFIX=/app_03/api +``` + +**Vite proxy 配置(开发环境):** +```typescript +// vite.config.ts +server: { + proxy: { + [apiPrefix]: { // "/app_03/api" + target: 'http://localhost:8030', + changeOrigin: true, + rewrite: (path) => path.replace(/^\/app_03\/api/, '/api'), + }, + }, +} +``` + --- ## 四、后端规范 diff --git a/frontend/.env.example b/frontend/.env.example index 1eb9564..e979412 100644 --- a/frontend/.env.example +++ b/frontend/.env.example @@ -1,3 +1,2 @@ VITE_API_PREFIX=/app_03/api VITE_UPLOADS_PREFIX=/uploads - diff --git a/frontend/src/app/services/api.ts b/frontend/src/app/services/api.ts index 7a5f8c9..8a90307 100644 --- a/frontend/src/app/services/api.ts +++ b/frontend/src/app/services/api.ts @@ -2,7 +2,8 @@ const TOKEN_KEY = "auth_token"; const env = (import.meta as any).env || {}; const API_PREFIX: string = (env.VITE_API_PREFIX as string) || "/api"; -const APP_BASE_URL: string = (env.BASE_URL as string) || "/"; +// APP_BASE_URL = basename = 从 API_PREFIX 提取("/app_03/api" → "/app_03") +const APP_BASE_URL: string = API_PREFIX.replace(/\/api\/?$/, '') || '/'; function joinPrefix(prefix: string, path: string) { const p = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix; diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index fcac799..ac2d4fb 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -33,11 +33,12 @@ export default defineConfig(({ mode }) => { allowedHosts: ['.trycloudflare.com', '.loca.lt'], proxy: { [apiPrefix]: { - target: 'http://localhost:8000', + target: 'http://localhost:8030', changeOrigin: true, + rewrite: (path) => path.replace(/^\/app_03\/api/, '/api'), }, [uploadsPrefix]: { - target: 'http://localhost:8000', + target: 'http://localhost:8030', changeOrigin: true, }, },