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
相关产品推荐
相关产品推荐

