0

I'm trying to enable CORS with Amazon's API gateway and Lambda, but I keep getting the error.

Access to XMLHttpRequest at 'https://<url>' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I've followed https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html and added this to lambda expression:

        statusCode : statusCode,
        body: responseBody,
        headers: {
            'Content-Type': 'application/json', 
            'Access-Control-Allow-Origin': '*' 
            "Access-Control-Allow-Headers": "Content-Type",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
        }

I've also gone to the API gateway and clicked the enable CORS button. If I look at the OPTIONS in the API gateway it says the Access-Control-Allow-Headers is present

If I run a test on the API gateway I can see the headers returned by the lambda expression and the expected headers are all there, but I'm still getting the same error message.

edit: Logwatch isn't printing anything so I'm assuming that it's not even making it to my lambda function.

I can hit the API successfully from POSTMAN and it has the CORS headers

Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: OPTIONS,POST,GET

Here are the response headers I'm getting when I try in chrome.

content-length: 35
content-type: application/json
date: Sun, 03 May 2020 01:51:15 GMT
status: 400
x-amz-apigw-id: L7p_IEbuoAMFeaA=
x-amzn-errortype: BadRequestException
x-amzn-requestid: 7ed06b7d-951f-4774-9bfa-62f307ee5974
StaticMethod
  • 593
  • 1
  • 7
  • 20
  • 1
    What about other headers in options, not only `Access-Control-Allow-Headers`. Also what method do you use,. if `ANY` then this requires [special treatment](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors-console.html): "ANY method in a proxy integration, any applicable CORS headers will not be set." – Marcin May 02 '20 at 23:39
  • I'm just using POST. The Method Response section of the API gateway says it has the following headers for 200. Name Access-Control-Allow-Headers Access-Control-Allow-Methods Access-Control-Allow-Origin – StaticMethod May 03 '20 at 01:17

1 Answers1

1

The problem is that I was POSTing the data incorrectly from my UI so it was failing model validation. After I disabled body validation it started working properly.

See this question: AWS API Gateway - CORS + POST not working

StaticMethod
  • 593
  • 1
  • 7
  • 20