LoginSignup
80
63

More than 5 years have passed since last update.

Serverlessを使ってAPI GatewayとLambdaでCORSを有効にする

Last updated at Posted at 2016-11-11

公式ドキュメントに書いてあるままなのですがドハマリしたのでメモ :joy:
https://serverless.com/framework/docs/providers/aws/events/apigateway#enabling-cors

sls create --template aws-node でプロジェクトを作って…

serverless.yml で cors: true を設定する

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: user/create
          method: get
          cors: true

lambdaのレスポンスの headersAccess-Control-Allow-Origin を設定する

exports.handler = function(event, context, callback) {

    const response = {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin" : "*" // Required for CORS support to work
      },
      body: JSON.stringify({ "message": "Hello World!" })
    };

    callback(null, response);
};

これだけです! :joy:
serverless.ymlに cors: true を設定したのでServerlessでのCORS設定はちゃんとしたと思いこんでたら、lambdaのレスポンスにもCORSヘッダを設定しないといけなかった…!
serverless.ymlのほうはAPI Gatewayで、lambdaのCORS設定はlambdaのソース内に書くと考えれば納得かも?
ついでにその他にもハマったポイントも書いておきます。

lambdaのレスポンスは statusCode, headers, body が無いとダメ

よくあるHTTPクライアントと違って、callback(null, response);response にbodyになるものを適当に突っ込んでおけば良いって感覚じゃダメなんですね。

lambdaのレスポンスの bodystring じゃないとダメ

const response = {
      statusCode: 200,
      headers: {},
-      body: { "message": "Hello World!" }
+      body: JSON.stringify({ "message": "Hello World!" })
    };

↓みたいなエラーがAPI Gatewayで出たら、body にJSONをそのまま突っ込んでいるかも。

Execution failed due to configuration error: Malformed Lambda proxy response
Wed Oct 26 01:35:28 UTC 2016 : Method completed with status: 502

lambdaとして有効でもAPI Gatewayとつなぐには良くないコードだったりするのがややこしいのかな :thinking:

80
63
1

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
80
63