python config_error ai_generated true

运行时错误:缺少 CORS 头。请使用 'Access-Control-Allow-Origin' 头。

RuntimeError: CORS headers are missing. Use 'Access-Control-Allow-Origin' header.

ID: python/starlette-cors-missing-headers

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

版本兼容性

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

根因分析

Starlette 不会自动添加 CORS 头;您必须使用像 CORSMiddleware 这样的中间件。

English

Starlette does not automatically add CORS headers; you must use a middleware like CORSMiddleware.

generic

解决方案

  1. 95% 成功率 Add CORSMiddleware to the application
    from starlette.middleware.cors import CORSMiddleware
    app.add_middleware(CORSMiddleware, allow_origins=['*'])
  2. 90% 成功率 Use the CORSMiddleware with specific origins
    app.add_middleware(CORSMiddleware, allow_origins=['https://example.com'], allow_methods=['GET'])

无效尝试

常见但无效的做法:

  1. Manually setting headers in each response 70% 失败

    Preflight OPTIONS requests are not handled.

  2. Using a custom middleware that only adds headers on some routes 60% 失败

    CORS must be applied globally.