FastAPI CORS跨域
在 FastAPI 应用中使用 CORSMiddleware 来配置它。
导入 CORSMiddleware。
创建一个允许的源列表(由字符串组成)。
将其作为「中间件」添加到你的 FastAPI 应用中。
指定后端是否允许
凭证(授权 headers,Cookies 等)。
特定的 HTTP 方法(POST,PUT)或者使用通配符 "*" 允许所有方法。
特定的 HTTP headers 或者使用通配符 "*" 允许所有 headers。
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["GET"],
allow_headers=["*"],
)
@app.post("/")
def main():
return {"message": "Hello World"}
Last updated