0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

API Gateway(SAM)にPOSTしたらOPTIONSだよって怒られた時の対処

Last updated at Posted at 2020-05-23

事象

ウェブページからAjaxでJSONをAPIGatewayにPOSTすると、メソッドがPOSTではなくOPTIONSに変わり拒否される。

AWS SAM LocalでのAPI開発で裏側にはLambdaがいるというようシチュエーションです。

スクリーンショット 2020-05-23 18.30.31.png

Ajaxリクエストをしたウェブページでは↓↓のように怒られてる。

スクリーンショット 2020-05-23 18.30.08.png

結論

APIGatewayにCORSを許可する設定する事で解決。

AWS公式のドキュメントにある通りSAMテンプレートに下記を記述する事で解決。

Globals:
  Api:
    # Allows an application running locally on port 8080 to call this API
    Cors:
      AllowMethods: "'OPTIONS,POST,GET'"
      AllowHeaders: "'Content-Type'"
      AllowOrigin: "'http://localhost:8080'" # "'*'"でもいけた

lambdaからの結果をPOSTしたウェブページで受け取りたい場合は、lambdaのレスポンスを下記のようにする。
じゃないと、POSTは出来てもレスポンスを受け取れ無い。

// node.jsの場合
return {
    'statusCode': 200,
    'headers': {
        "Access-Control-Allow-Origin": "http://localhost:8080" // "'*'"でもいけた
    },
    'body': json.dumps(response)
}

原因

ざっとした原因は、ブラウザによるプリフライトという仕組みのせい。
疎通テストのようなもので、これにつまずいていた。

なので、プリフライトを受け付ける設定をAPIGatewayにする必要がある。

終わりに

最初に”axios post出来ない”みたいな感じでフロント側を疑ってしまい解決まで遠回りしました。。。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?