You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI:如何仅为特定端点启用CORS?

FastAPI 仅为特定端点启用CORS

默认的CORSMiddleware会对所有端点生效,要实现仅特定或单个端点开启CORS,可以用以下两种实用方法:

方法一:自定义CORS中间件

通过自定义中间件判断请求路径,仅对目标端点添加CORS响应头:

from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware

app = FastAPI()

# 定义需要开启CORS的端点路径列表
ALLOWED_CORS_PATHS = ["/specific-endpoint", "/another-target-endpoint"]

class CustomCORSMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        response = await call_next(request)
        # 匹配目标路径则添加CORS头
        if request.url.path in ALLOWED_CORS_PATHS:
            response.headers["Access-Control-Allow-Origin"] = "*"
            response.headers["Access-Control-Allow-Methods"] = "GET, DELETE"
            response.headers["Access-Control-Allow-Headers"] = "*"
            response.headers["Access-Control-Max-Age"] = "0"
        return response

app.add_middleware(CustomCORSMiddleware)

# 测试端点
@app.get("/specific-endpoint")
async def specific_endpoint():
    return {"message": "该端点已启用CORS"}

@app.get("/normal-endpoint")
async def normal_endpoint():
    return {"message": "该端点无CORS配置"}

方法二:用依赖项给单个端点加CORS头

针对单个或少量端点,创建依赖项在响应中注入CORS头:

from fastapi import FastAPI, Depends
from starlette.responses import Response

app = FastAPI()

def add_cors_headers(response: Response):
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Methods"] = "GET, DELETE"
    response.headers["Access-Control-Allow-Headers"] = "*"
    response.headers["Access-Control-Max-Age"] = "0"

# 仅该端点启用CORS
@app.get("/single-cors-endpoint", dependencies=[Depends(add_cors_headers)])
async def single_cors_endpoint():
    return {"message": "单个端点已开启CORS"}

@app.get("/no-cors-endpoint")
async def no_cors_endpoint():
    return {"message": "该端点无CORS配置"}

注意事项

  • 若需处理OPTIONS预检请求,自定义中间件需额外编写OPTIONS请求的响应逻辑;依赖项方式可配合FastAPI自动处理OPTIONS的机制,或手动添加OPTIONS路由。
  • 生产环境建议限制具体的allow_origins值,而非使用通配符*。

内容的提问来源于stack exchange,提问作者Hazem Alrfati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:01:00