React+FastAPIでWebサイトを作成しました。FastAPI側では公式ドキュメントを読んでCORS対策しましたが、CORSエラーが出てデータをサーバーに送れません。何が原因なのでしょうか?
特徴
1.POST送信時のみエラーが出る。(GETメソッドでは起きない。)
2.ローカル環境(ReactとFastAPIは別ポート)ではPOST, GETとも問題なく動作する。
3.デプロイした環境でのみエラーが発生する。
コード
React
fetch('FastAPIのデプロイ先のURL', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'data': data,
})
});
FastAPI
app = FastAPI()
origins = [
'http://localhost:3000',
'Reactのデプロイ先のURL'
]
app.add_middleware(
CORSMiddleware,
allow_origins = origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
@app.post('/api/someapi')
async def result(item: dict = Body(...)):
do_something(item['data'])
return {"message": "Hello World"}
コードの詳細
フロントエンド側でボタンを押すと、FastAPIにデータを送信、DB操作をしたのち、無意味なresponseを返す。
エラーの詳細
Webブラウザのコンソールに
Access to fetch at 'FastAPIのURL' from origin 'ReactのURL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
試したこと
1.return文で何も返さない、
2.JSONResponseヘッダーに直接'Access-Control-Allow-Origin'で許可を与える。