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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With