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



下面的示例将为应用程序中的所有端点启用CORS。如何仅为特定的启用CORS端点,或只是一个单独的端点,使用FastAPI?

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=False,
allow_methods=["GET","DELETE"],
allow_headers=["*"],
max_age=0
)

您可以只使用创建一个Sub应用程序您希望从不同的源而不是后端访问的端点,并将CORSMiddleware添加到该子应用程序.

请注意,如本回答中所述,在allow_origins参数中使用'*'通配符(如您的问题所示)-而不是像这里所示指定特定的起源-将意味着所有起源被允许;然而,代价是排除所有涉及凭证的内容,例如cookie授权标头等;因此,将allow_credentials参数设置为True(参见Access-Control-Allow-Credentials响应头文档)将没有效果,并且当执行跨域请求时,您仍然无法在客户端和服务器之间发送/接收凭据(例如上面描述的凭据)(参见这里和这里了解更多细节)。

工作示例

可以通过http://127.0.0.1:8000/subapi/sub

访问下例中subapi(子应用程序)的/sub端点
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
subapi = FastAPI()
# specify the origins from which you wish the backend (subapi) to be accessible 
origins = ['http://localhost:3000']  
subapi.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
)

@app.get('/app')
def read_main():
return {'message': 'Hello World from main app'}


@subapi.get('/sub')
def read_sub():
return {'message': 'Hello World from sub API'}

app.mount('/subapi', subapi)

最新更新