Browse Source

fix(openapi): 预览页 Try it out 走同源代理,servers 默认不再指向生产

Swagger UI 传了 withCredentials,带凭据的跨域请求不接受后端的
Access-Control-Allow-Origin: *,浏览器直接拦截报 Failed to fetch。
不动后端 CORS 配置(会影响生产),改成和 dashboard-v6 一样走同源代理:

- vite.config.ts 加 /api -> http://127.0.0.1:8000 的 proxy,
  可用 VITE_API_TARGET 覆盖目标
- servers 增加相对地址 /api,并调整顺序为 同源 -> 本地直连 -> 测试 -> 生产。
  原先生产排第一,而 Swagger UI 默认选中第一项,点 Try it out 会直接打生产库

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
visuddhinanda 3 tuần trước cách đây
mục cha
commit
a976d908ed

+ 9 - 6
openapi/public/assets/protocol/main.yaml

@@ -10,17 +10,20 @@ info:
   version: 2026.9.21
 servers:
   -
-    url: 'https://www.wikipali.org/api'
-    description: 生产
+    url: /api
+    description: '同源(预览页里 Try it out 走 vite 代理,避免跨域)'
   -
-    url: 'https://www.wikipali.cc/api'
-    description: 生产(中国)
+    url: 'http://127.0.0.1:8000/api'
+    description: '本地开发(直连,浏览器里会被 CORS 挡住)'
   -
     url: 'https://staging.wikipali.org/api'
     description: 测试
   -
-    url: 'http://127.0.0.1:8000/api'
-    description: 本地开发
+    url: 'https://www.wikipali.org/api'
+    description: 生产
+  -
+    url: 'https://www.wikipali.cc/api'
+    description: 生产(中国)
 components:
   securitySchemes:
     bearerAuth:

+ 4 - 2
openapi/scripts/generate.php

@@ -689,11 +689,13 @@ $main = [
             "响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。",
         'version' => date('Y.n.j'),
     ],
+    // 第一项是 Swagger UI 的默认选择,放同源代理,避免 Try it out 误打生产
     'servers' => [
+        ['url' => '/api', 'description' => '同源(预览页里 Try it out 走 vite 代理,避免跨域)'],
+        ['url' => 'http://127.0.0.1:8000/api', 'description' => '本地开发(直连,浏览器里会被 CORS 挡住)'],
+        ['url' => 'https://staging.wikipali.org/api', 'description' => '测试'],
         ['url' => 'https://www.wikipali.org/api', 'description' => '生产'],
         ['url' => 'https://www.wikipali.cc/api', 'description' => '生产(中国)'],
-        ['url' => 'https://staging.wikipali.org/api', 'description' => '测试'],
-        ['url' => 'http://127.0.0.1:8000/api', 'description' => '本地开发'],
     ],
     'components' => [
         'securitySchemes' => [

+ 10 - 0
openapi/vite.config.ts

@@ -5,4 +5,14 @@ import react from "@vitejs/plugin-react";
 export default defineConfig({
   plugins: [react()],
   base: "/protocols/",
+  server: {
+    // Swagger UI 带 withCredentials 发请求,跨域时后端的 Access-Control-Allow-Origin: *
+    // 会被浏览器拒绝。这里代理成同源请求,"Try it out" 就能直接打本地后端。
+    proxy: {
+      "/api": {
+        target: process.env.VITE_API_TARGET ?? "http://127.0.0.1:8000",
+        changeOrigin: true,
+      },
+    },
+  },
 });