0
0

More than 1 year has passed since last update.

LambdaにFastAPIのDockerイメージを参照して発行した関数URLからCORSエラーが生じる

Posted at

下記のようにFastAPIのapp.pyファイルにてadd_middlewareのCORS設定にてワイルドカードのアスタリスク指定をしているのですがCORSエラーが返ってきます。

app.py
"""サーバー立ち上げ"""
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import uvicorn
import os
from mangum import Mangum

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_origin_regex="https?://.*",
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
handler = Mangum(app)


def hello_world(text: str):
    return "hello world" + text


@app.get("/")
def my_function():
    """ハローワールドtest"""
    greed = hello_world("test")
    return JSONResponse({"text": greed})

検索してみるとAWS API Gatewayと連携した際のエラー対処法が出てくる

AWSはAPI Gatewayというサービスの中でLambdaを立てることができるのですがその使い方でInternal Server 500エラーが生じやすいそうです。

しかし今回はLambda単体で生じているため解決策にはなりませんでした。

Lambda側でcors設定ができた

そもそもFastAPI側でCORS設定するのではなくLambda側で設定する必要がありました。
そういえばチュートリアルで設定したことがあったのですが忘れていました。

スクリーンショット 2023-05-08 15.08.50.png

スクリーンショット 2023-05-08 15.10.52.png

このページの編集画面で適当に編集すればCORSを有効化して使えるようになります。
スクリーンショット 2023-05-08 15.11.01.png

適当に許可オリジンを決めれば解消します。
もっともその後に発生した違うエラーに苦しんでいる現在ですが。

スクリーンショット 2023-05-08 15.13.25.png

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