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?