0

How do you enable CORS so you can access to a custom AWS API Gateway from jQuery?

I've exposed a simple Python Lambda function through an API Gateway to lookup user data, and I'm trying to access its endpoint with jQuery like:

$.ajax({
    method: 'GET',
    url: 'https://slkdfjsl.execute-api.us-east-1.amazonaws.com/myapi/username?_='+new Date().getTime(),
    headers: {
        Authorization: authToken
    },
    data: {},
    contentType: 'application/json',
    success: function(result){
        //do stuff
    }
});

Sometimes, this works perfectly. Sometimes, I get the error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://slkdfjsl.execute-api.us-east-1.amazonaws.com/myapi/username?_=1606336278598  (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

what would be causing this?

What I don't understand is the non-deterministic nature of this. Answers to similar questions have explained that you might need to add:

async: true,
dataType: 'jsonp',
crossDomain: true,

to the ajax() call to enable cross-domain access, but that wouldn't explain why the code without this works most of the time.

I tried adding those options, and that completely breaks it 100% of the time, giving me a "401 unauthorized" error every time.

Is there someway to fix this in my code, or is this potentially a bug with the AWS API Gateway implementation?

Cerin
  • 60,957
  • 96
  • 316
  • 522

1 Answers1

0

Cross Domain (CORS) should be allowed at backend and not in ajax call.

Try following.

A. CORS SETTINGS AT AWS GATEWAY OR API RESPONSE

You need to enable CORS either

  1. AWS API Gateway CORS settings from API Gateway console. (https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors-console.htm)

  2. You need to return CORS headers within the response to your API

If both are done together, Point 1 takes priority.

Headers that need to be set are '''

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.

'''

If you think your settings are correct, make sure that the following points are taken care of.

B.NULL ORIGIN Your local application (client for API) must be hosted on a web-server. If you are running it directly from the file system, you have a null origin. In AWS CORS settings, the null origin is never allowed.

C. API URL must exist CORS is not allowed for the API that does not exist. So make sure that your API URL is correct. In this case, you may not get API does exist error (if the error is in a subpath). Check if you need a slash / at the end.

Sandeep Dixit
  • 799
  • 7
  • 12