Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable CORS using aws cdk? I keep getting No "Access-Control-Allow-Origin"

I created a lambda and apigateway using aws cdk. It works fine from postman.

When I make a post call from the browser i get No "Access-Control-Allow-Origin".

So I am trying to enable CORS in API Gateway, using the CDK. I am doing it the following way:

// users microservice api gateway
    const apiGateway = new LambdaRestApi(this, "usersApi", {
      restApiName: "Users Service",
      handler: microServices.fn,
      proxy: false,
    });

    // creating resources
    const users = apiGateway.root.addResource("users");
    users.addMethod("POST");
    users.addCorsPreflight({
      allowOrigins: ["*"],
      allowHeaders: ["*"],
      allowMethods: ["*"],
    });

But I still get No "Access-Control-Allow-Origin".
What am I missing? How do I enable CORS via the cdk?

like image 410
Moyshe Zuchmir Avatar asked Sep 12 '25 15:09

Moyshe Zuchmir


1 Answers

Your lambda has to put CORS headers in its response.

For example:

return {
    isBase64Encoded: false,
    statusCode: 200,
    body: JSON.stringify('success'),
    headers: {
        'Access-Control-Allow-Headers': 'Content-Type',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'OPTIONS,POST',
    }
}

reference - see Enabling CORS support for Lambda or HTTP proxy integrations section

https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

like image 118
gshpychka Avatar answered Sep 14 '25 06:09

gshpychka