Files
aiagent/修复说明.md
2026-01-19 00:09:36 +08:00

84 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# CORS和Private Network Access问题修复
## 问题原因
浏览器阻止了从公网IP (`101.43.95.130:8038`) 访问 `localhost:8037` 的请求,这是浏览器的**Private Network Access (PNA)**安全策略。
错误信息:
```
Access to XMLHttpRequest at 'http://localhost:8037/api/v1/auth/register'
from origin 'http://101.43.95.130:8038' has been blocked by CORS policy:
The request client is not a secure context and the resource is in more-private address space `local`.
```
## 解决方案
### 1. 前端API地址自动推断 ✅
修改了 `frontend/src/api/index.ts`,使其能够:
- 检测当前访问的主机名
- 如果是从公网IP访问自动使用相同的IP地址访问后端
- 例如:前端在 `101.43.95.130:8038`,后端自动使用 `101.43.95.130:8037`
### 2. 后端CORS配置 ✅
已在后端配置中允许来自 `http://101.43.95.130:8038` 的请求。
### 3. 后端监听地址 ✅
确保后端监听在 `0.0.0.0:8000`(容器内),映射到主机的 `8037` 端口。
## 验证步骤
1. **刷新浏览器页面**(清除缓存)
2. **打开浏览器控制台**,查看是否有新的错误
3. **尝试注册**应该不再出现CORS错误
## 如果仍有问题
### 检查1后端是否可访问
```bash
# 从服务器测试
curl http://101.43.95.130:8037/health
# 应该返回: {"status":"healthy"}
```
### 检查2CORS响应头
```bash
curl -X OPTIONS http://101.43.95.130:8037/api/v1/auth/register \
-H "Origin: http://101.43.95.130:8038" \
-H "Access-Control-Request-Method: POST" \
-v
```
应该看到 `Access-Control-Allow-Origin: http://101.43.95.130:8038` 响应头。
### 检查3防火墙
确保服务器的8037端口对外开放
```bash
# 检查端口是否开放
netstat -tlnp | grep 8037
# 或
ss -tlnp | grep 8037
```
### 检查4浏览器控制台
打开浏览器开发者工具F12查看
- Network标签检查实际请求的URL
- Console标签查看是否有新的错误信息
## 关键点
**重要**前端从公网IP访问时**绝对不能**使用 `localhost` 作为后端地址必须使用相同的公网IP地址。
---
**状态**: ✅ 已修复
**时间**: 2024年