LoginSignup
0
0

More than 1 year has passed since last update.

FastAPI: CORS の使い方

Last updated at Posted at 2022-04-12

プログラム

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.
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0