XMLHttpRequest cannot load https://???.execute-api.ap-southeast-???.amazonaws.com/beta/??? Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present

I received this error in the browser (Chrome in this case) when building a ‘GET’ API GATEWAY method for a resource.

When the browser attempts to call the API GATEWAY resource method, it may do an OPTIONS request before making a call to other methods such as POST, GET, PUT etc.

A very good article that explains CORS and OPTIONS is here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

The important point for me was:

browsers “preflight” the request, soliciting supported methods from the server with an HTTPOPTIONS request method, and then, upon “approval” from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether “credentials” (including Cookies and HTTP Authentication data) should be sent with requests. ]

In my case I had the ‘GET’ method but no ‘OPTIONS’ method specified for my API GATEWAY resource.

Essentially, the browser was sending a request to the API GATEWAY using an OPTIONS request – saying – ‘server, can I call you, what do you support, etc’. Because there was no OPTIONS method present on my resource, the browser was getting an unsatisfactory response and produced the error (which is the title of this post).

The simplest solution is to:

Click on the resource in the AWS console -> Click ‘Actions’ -> Click ‘Enable CORS’.

This adds the OPTIONS method and appropriate settings to your resource methods.

This should allow the browser to receive a satisfactory response from the API GATEWAY when sending an OPTIONS request.

The three most important headers returned when OPTIONS is set correctly are:

  1. Access-Control-Allow-Headers: Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token
  2. Access-Control-Allow-Methods: GET,OPTIONS
  3. Access-Control-Allow-Origin: *

Notice Access-Control-Allow-Origin has the setting of ‘*’.

 

CORS AND API GATEWAY LAMBDA PROXY INTEGRATION

Enabling CORS

To enable CORS when creating a Lambda Proxy Integration API, you must add the following code to the LAMBDA function:

headers: {
“Access-Control-Allow-Origin” : “*” // Required for CORS support to work
}

So an example payload might be:

var response = {
statusCode: 200,
headers: {
“Access-Control-Allow-Origin” : “*” // Required for CORS support to work
},
body: JSON.stringify({
payload: “My payload”
})
};

This took me a lot searching to find! This certainly helped: servless.com/…