fix: avoid loopback api base on public web origin

This commit is contained in:
chengkai3
2026-04-12 23:09:52 +08:00
parent c2505eb70c
commit 3fbd603eae
6 changed files with 72 additions and 8 deletions
+17
View File
@@ -214,3 +214,20 @@
- 注册显示 `注册`
- 验证:
- 复跑 `docker compose build web`,构建成功,路由静态生成完成,最终输出 `fquiz-web Built`
## 追加修复(浏览器 PNA 阻断导致登录失败)
- 触发问题:
- 浏览器报错:从 `http://223.109.142.84:3000` 访问 `http://127.0.0.1:8000` 被拦截,提示
`The request client is not a secure context and the resource is in more-private address space loopback`
- 根因:
- 前端构建时注入 `NEXT_PUBLIC_API_BASE_URL=http://127.0.0.1:8000`,线上浏览器会把 `127.0.0.1` 解释为“访问者本机回环地址”,触发 PNA 安全策略阻断。
- 处理:
- 新增前端 API 基址运行时解析(`web/src/lib/api.ts`):
- 浏览器端若发现配置为 loopback(`127.0.0.1/localhost`),且当前页面不在 loopback 主机,则自动改写为当前页面主机 + 原端口(默认 `8000`)。
- 认证请求统一走运行时 API 基址(`web/src/components/auth-provider.tsx`)。
- WS 连接统一走运行时 API 基址(`web/src/components/ws-provider.tsx`)。
- 首页 `Ping` 与 API Base 展示改为运行时解析值(`web/src/app/page.tsx`)。
- 验证:
- `cd web && npx eslint src/lib/api.ts src/components/auth-provider.tsx src/components/ws-provider.tsx src/app/page.tsx` 通过。
- `cd web && npx tsc --noEmit` 通过。