You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI-React项目CORS跨域访问失败,求解决方案

求助:FastAPI-React项目CORS跨域问题未解决

此问题已有较多相关文档,但我尝试多种方法均未解决,恳请各位提供建议!

  • 相关Cookiecutter项目:Buuntu/fastapi-react

错误重现步骤

cookiecutter gh:Buuntu/fastapi-react --no-input
cd fastapi-react-project

运行构建脚本前修改的文件(用于解决之前的错误):

  • 修改frontend/Dockerfile第7行:
RUN npm install --legacy-peer-deps
  • 注释docker-compose.yml第37行的flower服务:
# flower:
  #   image: mher/flower
  #   command: celery flower --broker=redis://redis:6379/0 --port=5555
  #   ports:
  #       - 5555:5555
  #   depends_on:
  #     - "redis"

执行构建脚本:

cd fastapi-react-project
chmod +x scripts/build.sh
./scripts/build.sh

后续操作:

  • 打开页面:http://0.0.0.0:8000/
  • 点击按钮:"Click to make request to backend"

触发的错误:

Access to fetch at 'http://localhost:8000/api/v1' from origin 'http://0.0.0.0:8000' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space local.

GET http://localhost:8000/api/v1 net::ERR_FAILED api.ts:4 <-- fetch()

已尝试的解决方法

  • 在Nginx配置中添加Access-Control-Allow-Origin头
  • 在React项目的package.json中配置proxy
  • 在fetch请求中添加no-cors模式
  • 给FastAPI应用配置CORSMiddleware中间件

系统信息

➜ uname -v
# Darwin Kernel Version 21.6.0: Wed Aug 10 14:25:27 PDT 2022; root:xnu-8020.141.5~2/RELEASE_X86_64
➜ docker-compose version
# Docker Compose version v2.13.0

补充信息

  • 可参考项目中的nginx.conf配置

内容的提问来源于stack exchange,提问作者willwrighteng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 23:25:57