Search code examples
amazon-web-servicesaws-lambdaaws-api-gateway

Why do I get a CORS error on AWS Api Gateway & Lambda POST?


I am getting a CORS error for my POST/PUT requests to AWS Api Gateway URL, that trigger lambda functions. GET request works.

I have already created an additional mock OPTIONS with

const response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,X-Amz-Security-Token,Authorization,X-Api-Key,X-Requested-With,Accept,Access-Control-Allow-Methods,Access-Control-Allow-Origin,Access-Control-Allow-Headers",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "X-Requested-With": "*"
        },
        body: JSON.stringify(''),
    };

for the same url as the post request for the preflight requests. Network tab in the dev console shows that preflight call returns a 200, console still tells me this: enter image description here

with a CORS error. I also return the same headers as above with the POST/PUT response.

I also have configured CORS in Api Gateway for the api.

Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: content-type,x-amz-date,x-amz-security-token,authorization,x-api-key,x-requested-with,accept,access-control-allow-methods,access-control-allow-origin,access-control-allow-headers
Access-Control-Allow-Methods: *

Does anybody have an idea what I have to change for it to work?


Solution

  • Please make sure to pass below headers from every lambda response

    "headers": {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials": "true",
    }
    

    Also, you need to enable CORS from API Gateway (select all the verbs there like POST and OPTIONS) with '*' origin which will create an options resource in the same path. Working for me like that