FastAPI中怎么實(shí)現(xiàn)跨源資源共享

小億
100
2024-05-10 16:40:57

要在FastAPI中實(shí)現(xiàn)跨源資源共享(CORS),可以使用FastAPI提供的CorsMiddleware中間件。以下是一個(gè)簡(jiǎn)單的示例:

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

app = FastAPI()

# 允許所有來(lái)源的請(qǐng)求
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中間件。我們?cè)O(shè)置了allow_origins["*"],表示允許所有來(lái)源的請(qǐng)求。同時(shí)設(shè)置了allow_credentialsTrue,表示允許發(fā)送憑據(jù)(例如cookies)。

通過(guò)上述步驟,在FastAPI應(yīng)用程序中就啟用了CORS功能,允許跨源資源共享。

0