Flask-Cors配置需严格遵循规范:origins必须为明确协议+域名+端口的列表;动态校验需处理None并返回布尔值;预检请求须显式声明methods和allow_headers;启用credentials时origins不能为*且必须配expose_headers。

Flask-Cors 的 origins 参数必须传入字符串或列表,不能写成通配符加条件判断
很多人误以为 origins="https://example.com" 就能只允许该域名,结果发现前端仍被拦截——其实是因为 Flask-Cors 默认不校验协议、端口、子路径,且 origins 值若为字符串,Flask-Cors 会当作正则表达式处理(即使没写 ^ 或 $),导致意外匹配。正确做法是明确传入列表,并确保协议、域名、端口完全一致。
- ✅ 正确:
origins=["https://api.example.com", "https://admin.example.com:8080"] - ❌ 错误:
origins="https://example.com"(会被当正则,可能匹配https://badexample.com) - ❌ 错误:
origins=["example.com"](缺少协议和端口,浏览器预检失败)
使用 lambda 函数动态校验 origin 时,必须返回布尔值且处理 None 情况
当需要根据请求头中的 Origin 做白名单校验(比如读取数据库或配置中心),得用 callable 类型的 origins。但容易忽略两点:一是请求可能没有 Origin 头(如 curl 测试或同源请求),此时 origin 参数为 None;二是函数必须明确返回 True 或 False,不能抛异常或返回字符串。
- ✅ 安全写法:
def check_origin(origin): if origin is None: return False allowed = ["https://app.example.com", "https://staging.app.example.com"] return origin in allowed - ❌ 常见翻车:
return origin.endswith("example.com")(会放行https://evil.example.com) - ⚠️ 注意:Flask-Cors 不缓存 callable 的返回结果,高频请求下建议加本地缓存或用集合
in判断
CORS 预检请求(OPTIONS)失败,大概率是没配 methods 或 allow_headers
前端发带自定义 header(如 Authorization)或非简单方法(PATCH、DELETE)时,浏览器先发 OPTIONS 预检。如果只设了 origins 却没指定 methods 和 allow_headers,预检会 403 或无响应。
- ✅ 必须显式声明:
methods=["GET", "POST", "PUT", "DELETE"] - ✅ 若前端带
Authorization:allow_headers=["Content-Type", "Authorization"] - ⚠️
allow_headers="*"在多数浏览器中不被允许(除简单 header 外),必须列明 - ? 调试技巧:用
curl -I -X OPTIONS -H "Origin: https://app.example.com" http://localhost:5000/api/data看响应头是否含Access-Control-Allow-Origin
生产环境禁用 supports_credentials=True 时未同步关闭 expose_headers 可能引发报错
当设置 supports_credentials=True(即允许前端带 cookie 请求),Flask-Cors 要求 origins 不能为 *,且必须显式声明 expose_headers 才能让前端读取响应头(如 X-Total-Count)。但很多人只加了 supports_credentials=True,却忘了配 expose_headers,结果前端 JS 报 Response header 'X-Total-Count' is not accessible from script。
- ✅ 正确组合:
cors = CORS(app, origins=["https://app.example.com"], supports_credentials=True, expose_headers=["X-Total-Count", "X-Request-ID"]) - ⚠️ 注意:
expose_headers是 list,不是字符串;空列表[]表示不暴露任何额外 header - ? 如果不需要读取自定义响应头,就别设
expose_headers,避免多余配置
实际部署时最容易漏的是预检请求的路由覆盖问题——比如用了蓝本(Blueprint)但只在全局初始化 CORS,而蓝本里某个视图没被覆盖到,或者用了 @cross_origin() 装饰器但忘记传参。这种问题不会报错,只会静默失效。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











