FastAPI中怎么实现跨源资源共享

1473
2024/4/22 16:40:57
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要在FastAPI中实现跨源资源共享(CORS),可以使用FastAPI提供的CorsMiddleware中间件。以下是一个简单的示例:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# 允许所有来源的请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def read_root():
    return {"message": "Hello, World"}

在上面的示例中,我们使用add_middleware方法添加了CorsMiddleware中间件。我们设置了allow_origins["*"],表示允许所有来源的请求。同时设置了allow_credentialsTrue,表示允许发送凭据(例如cookies)。

通过上述步骤,在FastAPI应用程序中就启用了CORS功能,允许跨源资源共享。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: FastAPI中怎么实现背景任务