Files
AIEC-new/AIEC-server/docs/cors-solution.md
2025-10-17 09:31:28 +08:00

2.2 KiB
Raw Permalink Blame History

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=["*"],
)

使用方法

  1. 重启 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 配置是否生效

  1. 重启 graph-rag-agent 后,访问测试页面:

    http://localhost:3000/test-graph-rag.html
    
  2. 或使用 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: *
    

注意事项

  1. 生产环境:不要使用 allow_origins=["*"],应该指定具体的允许域名
  2. 开发环境:当前配置允许所有源,方便开发测试
  3. SSE服务器发送事件:流式响应需要特别注意 CORS 配置