Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

公式ドキュメントに書いてあるままなのですがドハマリしたのでメモ :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:

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away