CORS Access-Control-Allow-Origin Header missing - Api Gateway HTTP / EC2

0

My backend setup for https://api.example.com is Route 53 -> Api Gateway HTTP API -> Cloud Map -> An EC2 instance running docker/django. When I make a fetch request from https://example.com, I get the error:

Access to fetch at 'https://api.example.com/foo' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

In API Gateway I've created /{proxy+} routes for POST, GET, PATCH, OPTIONS, all with integrations to my VPC.

For the CORS settings on my Api Gateway, I've set:

  • Access-Control-Allow-Origin: "*" (I'm only allowing all origins for testing purposes)
  • Access-Control-Allow-Headers: "*"
  • Access-Control-Allow-Method: POST, GET, PATCH, OPTIONS
  • Access-Control-Expose-Headers: "*"
  • Access-Control-Max-Age: 300

If I run curl http://{my-ec2-instance-public-ip}:8000/foo from my local terminal it returns the correct response, which makes me think the problem lies somewhere between API Gateway and the container.

Is there some other configuration setting I'm missing?

1 Answer
0

Hi Jacob,

I can see you've set your Access-Control-Allow-Headers configuration to * which is not a valid value and this could be the reason why you're request is getting blocked. You can only use * for Access-Control-Allow-Method and Access-Control-Allow-Origin, but not for Access-Control-Allow-Headers. You can check the AWS doco here https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html.

Try giving it a specific value, e.g., "Content-Type", etc. and hit your API Gateway again.

The reason why you're getting proper response using curl is because your request is coming through as a server or API client call, rather than a browser-based call, hence the CORS is not being triggered. My understanding of the document is that CORS is triggered only when a client is a browser.

Regards, Ed

answered a month ago
profile picture
EXPERT
reviewed a month ago
  • Hi Ed,

    Thanks for the suggestion! I updated the Access-Control-Allow-Headers as you suggested, but unfortunately I still get the same error.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions