python config_error ai_generated true

CORS 错误:预检请求的响应未通过访问控制检查:请求的资源上不存在 'Access-Control-Allow-Origin' 标头。

CORS error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

ID: python/fastapi-cors-not-enabled

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-06-05首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

FastAPI 应用未启用 CORS 中间件,导致浏览器阻止跨域请求。

English

FastAPI 应用未启用 CORS 中间件,导致浏览器阻止跨域请求。

generic

解决方案

  1. 95% 成功率
    from fastapi.middleware.cors import CORSMiddleware
    app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_methods=['*'], allow_headers=['*'])

无效尝试

常见但无效的做法:

  1. 60% 失败

    只处理了简单请求,预检请求(OPTIONS)仍然失败,且代码繁琐。

  2. 90% 失败

    Flask-CORS 是 Flask 的扩展,不兼容 FastAPI,会导致导入错误。