# CORS问题解决方案 ## 问题描述 前端从 `http://101.43.95.130:8038` 访问后端 `http://localhost:8037` 时,浏览器阻止了跨域请求。 错误信息: ``` Access to XMLHttpRequest at 'http://localhost:8037/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. 更新后端CORS配置 ✅ 在 `backend/app/core/config.py` 中添加了允许的来源: ```python CORS_ORIGINS: str = "http://localhost:3000,http://127.0.0.1:3000,http://localhost:8038,http://101.43.95.130:8038" ``` ### 2. 更新前端API地址 ✅ 修改了 `frontend/src/api/index.ts`,使其能够根据当前主机自动推断后端地址: - 如果前端运行在 `localhost`,后端使用 `http://localhost:8037` - 如果前端运行在公网IP(如 `101.43.95.130:8038`),后端使用 `http://101.43.95.130:8037` ### 3. 更新Docker Compose配置 ✅ 在 `docker-compose.dev.yml` 中: - 前端环境变量:`VITE_API_URL=http://101.43.95.130:8037` - 后端环境变量:添加 `CORS_ORIGINS` 配置 ## 验证 重启服务后,CORS问题应该已解决: ```bash # 重启服务 docker-compose -f docker-compose.dev.yml restart frontend backend # 验证CORS配置 curl -X OPTIONS http://localhost: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` 响应头。 ## 注意事项 1. **生产环境配置**:在生产环境中,应该: - 使用HTTPS - 限制CORS来源为实际的前端域名 - 不要使用 `*` 作为允许的来源 2. **API路径**:确保API路径正确: - 注册API:`/api/v1/auth/register`(不是 `/auth/register`) 3. **网络配置**:确保: - 后端服务监听在 `0.0.0.0:8037`(不是 `127.0.0.1`) - 防火墙允许8037端口访问 --- **状态**: ✅ 已修复 **时间**: 2024年