3

I created REST API using AWS API Gateway & AWS Lambda and when I configured CORS I faced with such issue - I was able to configure CORS response headers for OPTIONS method, but didn't for GET method.

I made it according Amazon documentation, but when I called GET method I didn't see required headers (Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Origin) in response. Due to that I got errors on client side:

Failed to load #my_test_rest#: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin #my_test_rest_url# is therefore not allowed access.

As a temporary fix I hardcode required headers in code of Lambda function, but it looks not like right solution and I'd like to understand why it don't work for me. Any ideas what's I'd doing wrong?

Hleb
  • 7,037
  • 12
  • 58
  • 117

1 Answers1

7

Since you're using Lambda Proxy integration for your method, you'll need to:

(1) provide the Access-Control-Allow-Origin header as part of the Lambda response. For example:

callback(null, {
    statusCode: 200,
    headers: {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"},
    body: JSON.stringify({message: "Success"})
});

(2) and add the Access-Control-Allow-Origin as a 200 response header in your Method Response config.

Khalid T.
  • 10,039
  • 5
  • 45
  • 53
  • That is exactly what I already did. But I think to hardcode headers in code of function is not a good idea, because it looks like the violation of single responsibility principle. I'm looking ways how to do that with API Gateway configuration only – Hleb Jan 31 '18 at 10:30
  • 1
    I totally agree but since the integration response is disabled for the proxy integration, you must rely on the back end to return the `Access-Control-Allow-Origin` header. – Khalid T. Jan 31 '18 at 11:02
  • For those who followed the above but still have issues. My API Gateway Resource still would fail after following the above when I set `API Key Required = true` for the resource method. After a few hours scratching my head and getting CORS `403` errors I discovered that if you require the api key with the resource method then you must create a Usage Plan in AWS to go along with the api key and resource. Once I set that up I could require the api key on the method and no longer received errors. – jhovanec Jan 23 '20 at 14:41