プログラム
main_cors.py
# ------------------------------------------------------------------
# main_cors.py
#
# Apr/12/2022
# ------------------------------------------------------------------
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
# ------------------------------------------------------------------
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:8080",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ------------------------------------------------------------------
@app.get("/")
def read_root():
return {"Hello": "World"}
# ------------------------------------------------------------------
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
# ------------------------------------------------------------------
サーバーの実行
uvicorn main_cors:app --reload
CORS の設定が出来ていないと次のようなエラーが出ます。
from origin 'https://example.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present
on the requested resource.