4
votes

I am using AWS API Gateway and Lambda Function for one of my applications.

When I send a POST request to API Gateway, it results in an error:

'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access. The response had HTTP status code 400

I enabled CORS in the API Gateway console and added 'Access-Control-Allow-Origin' to "Access-Control-Allow-Headers" and clicked "Enable CORS and replace existing CORS Header" button. It was a success.

But when I reloaded the page, I found 'Access-Control-Allow-Headers' header was not present in "Access-Control-Allow-Headers".

I don't know why AWS is not allowing me to edit "Access-Control-Allow-Headers".

2
Do you have OPTIONS method for resource?Yevhenii Herasymchuk
@YevheniiHerasymchuk Yesujjwal garg
are you sending correct headers in your POST request? please post your POST method.sid8491

2 Answers

3
votes

I enabled CORS in the API Gateway console and added 'Access-Control-Allow-Origin' to "Access-Control-Allow-Headers" and clicked "Enable CORS and replace existing CORS Header" button. It was a success.

OK, these are two entirely separate headers. Access-Control-Allow-Origin is a response header which must be sent in response to both preflight OPTIONS requests and the actual POST/GET requests. Access-Control-Allow-Headers is a separate response header which is only sent in response to a preflight OPTIONS request.

Can you provide a screenshot showing exactly what you entered where?

0
votes

I just enabled CORS for two of my APIs in AWS Gateway.

Even after enabling CORS in Gateway API CORS settings, I had faced CORS problem due to these reasons.

  1. CORS Settings: That's the starting point. In CORS settings on API Gateway allow CORS for you origin. Till you debug CORS issue, you may keep the least restrictive setting as shown below. Access-Control-Allow-Origin=*

Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE (you may even add all headers here during debugging)

Access-Control-Max-Age=0

Access-Control-Expose-Headers, Access-Control-Allow-Headers may be left as default.

  1. Null Origin: For local development, I was running my front-end application directly from the file system without a web-server. AWS CORS setting do not support null origin. I then hosted my local application on nodejs http-server. Now the application has origin localhost. And CORS setting worked fine on one of my APIs.

  2. API path must match. For the second API, I still faced the CORS issue. Despite have the same settings as other API and hosted on a web server. The problem here was that this API had integration at the root and for this case, API must end with /. It was very annoying that I was focusing only on CORS setting where the problem was somewhere else.

If CORS settings do not work for you, you may want to implement root OPTION and return proper CORS headers.