I’m struggling to get an AJAX call (using jQuery) to an AWS Lambda function working correctly, with slightly different behaviors on Firefox and Chrome. The lambda function itself works fine and I can load it both in testing and in my browser without any problem, so it’s just the AJAX that’s not working correctly. Here’s the relevant code below:
$.ajax({
url: lambdaUrl,
headers: {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'},
crossDomain: true,
type: 'POST',
data: dataToSend, // <-- Is a JSON object.
cache: false,
success: function(data) {
console.log({received: data});
},
error: function(data, statusText, xhr) {
console.log(data);
}
});
This is what’s being returned from the Lambda function:
var returnVal = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
},
body: JSON.stringify({
message: message,
success: success,
value: value,
}, null, 5),
};
return returnVal;
I’ve also configured the function for CORS in the YAML like so:
functions:
<functionname>:
handler: handler.<functionname>
events:
- http:
path: <functionname>
method: post
cors: true
In Firefox, the error function is called. When I print out the statusText, it just says “error” and the status is 0. The OPTIONS call in the network tab says it returned a 200, but the GET call never happens. I can’t seem to get any more information than that.
In Chrome, it says the request “has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.” There must be hundreds of “solutions” to this online, but none have made any difference at all. (Enabling CORS through the AWS Console opened up a whole new set of problems.)
I am using a VPC for an elastic IP. I’m not sure if that’s relevant, but I wanted to say it in case it is.
Does anybody have any idea what’s going on here?
Thanks.