繁体   English   中英

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

[英]FastAPI: How to enable CORS only for specific endpoints?

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

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
)

您可以创建一个子应用程序,其中仅包含您希望从与后端不同的来源访问的端点,并将CORSMiddleware仅添加到该子应用程序。 请注意,如本答案中所述,在allow_origins参数中使用'*'通配符(而不是像此处演示的那样指定特定来源)将意味着允许所有来源 但是,以排除所有涉及凭据的内容为代价,例如cookies授权标头等; 因此,将allow_credentials参数设置为True将无效。

工作示例

下面示例中subapi (子应用程序)的/sub端点可以在http://127.0.0.1:8000/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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM