2.2 KiB
2.2 KiB
CORS 问题解决方案
问题描述
当前端(运行在 localhost:3000)尝试访问 graph-rag-agent(运行在 localhost:8000)时,浏览器会阻止请求,因为违反了同源策略。
错误信息:
Access to fetch at 'http://localhost:8000/chat/stream' from origin 'http://localhost:3000' has been blocked by CORS policy
解决方案
方案1:修改 graph-rag-agent 的 CORS 配置(推荐)
我已经修改了 /home/jzhengda/graph-rag-agent/server/main.py,添加了 CORS 中间件:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 允许所有源
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
使用方法:
- 重启 graph-rag-agent 服务:
cd ~/graph-rag-agent # 先停止现有服务 (Ctrl+C) # 然后重新启动 python -m uvicorn server.main:app --reload --host 0.0.0.0 --port 8000
方案2:使用更安全的 CORS 配置
如果需要更安全的配置,可以使用 main_cors_specific.py,它只允许特定的源:
cd ~/graph-rag-agent/server
python -m uvicorn main_cors_specific:app --reload --host 0.0.0.0 --port 8000
方案3:使用浏览器插件(临时测试)
安装浏览器 CORS 插件(如 "CORS Unblock" 或 "Allow CORS"),仅用于开发测试。
方案4:配置反向代理
创建一个简单的反向代理,将前端和后端都代理到同一个端口下。
验证 CORS 配置是否生效
-
重启 graph-rag-agent 后,访问测试页面:
http://localhost:3000/test-graph-rag.html -
或使用 curl 测试:
curl -I -X OPTIONS http://localhost:8000/chat \ -H "Origin: http://localhost:3000" \ -H "Access-Control-Request-Method: POST"应该看到响应头中包含:
Access-Control-Allow-Origin: * Access-Control-Allow-Methods: *
注意事项
- 生产环境:不要使用
allow_origins=["*"],应该指定具体的允许域名 - 开发环境:当前配置允许所有源,方便开发测试
- SSE(服务器发送事件):流式响应需要特别注意 CORS 配置