AJAX seems to be unable to GET AWS API Gateway even with CORS enabled

875 views Asked by At

I have made an API Gateway which calls a lambda function on AWS. The link to GET it is:

https://z4eiy7g9n0.execute-api.us-east-1.amazonaws.com/test/rotation

Clicking it should return a number bigger than 6000. I want to use Javascript to GET the API and my understanding is I need to use AJAX to do that. So, I have the following javascript (importing jQuery 3.1.1):

$(document).ready(function(){
    $("button").click(function(){
        $.ajax({
         url: "https://z4eiy7g9n0.execute-api.us-east-1.amazonaws.com/test/rotation",
         headers: {"Content-Type": "text/json"},
         type: "GET",
         success: function() { alert('Success!'); }
      });
    });
});

This doesn't work because of cross-origin stuff and so my understanding is I need to enable CORS. So, I followed the instructions in http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html. I have

Access-Control-Allow-Origin*: '*'
Access-Control-Allow-Headers: 'Content-Type'

My understanding of this is that the origin can be any domain and the only header that needs to be included is 'Content-Type'. However, when I click my button to trigger this event, I get the following error in my console.

XMLHttpRequest cannot load https://z4eiy7g9n0.execute-api.us-east-1.amazonaws.com/test/rotation. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://****' is therefore not allowed access. The response had HTTP status code 403.

Now, I can call the API from R using the httr package, so I know it can be called from at least some systems.

What am I doing wrong with either my AJAX request or with my API?

2

There are 2 answers

0
Mark On BEST ANSWER

The problem was that I had not deployed the modified resources with CORS enabled. Once I deployed the resource, the javascript started working properly.

0
peter n On

I have successfully used AJAX to connect to a CORS-enabled API, and I don't remember passing content-type in the headers. Have you tried application/json instead of text/json? I believe this is how it gets configured by the CORS wizard on the AWS console.