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

Viewed 137

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?

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',
    }
}
Related