Skip to content

feat: 添加 CORS 配置支持环境变量 #17

Description

@lennney

问题

api/__init__.py:37 中 CORS origins 硬编码为 localhost:

allow_origins=["http://localhost:3000", "http://localhost:5173"]

部署到生产环境后,前端域名不在白名单中,会触发 CORS 错误。

修复方案

从环境变量读取 CORS origins:

import os

CORS_ORIGINS = os.getenv(
    "CORS_ORIGINS",
    "http://localhost:3000,http://localhost:5173"
).split(",")

app.add_middleware(
    CORSMiddleware,
    allow_origins=CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

.env.example 中添加:

# CORS (comma-separated origins)
CORS_ORIGINS=http://localhost:3000,http://localhost:5173,https://yourdomain.com

涉及文件

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions