Ajax call to Lambda function is failing

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:

    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) {

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:

        handler: handler.<functionname>
            - 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?


I ended up finding the solution here. It actually surprises me quite a bit-- Turns out the client-side shouldn’t have 'Access-Control-Allow-Origin': '*'. That should only be in the Lambda code, apparently, and adding it to the jQuery code will cause the preflight to fail for some reason.

Quick update: Also-- Although I found the solution before anybody had a chance to respond, I want to say thanks to this community. This is the third (I think) question I’ve asked on this board, and everyone here has been very friendly, welcoming, and helpful-- That hasn’t gone unnoticed on my part, and I’m grateful.