Reputation: 3831
I have backend services implemented in AWS Lambda (AWS::Serverless::Function + AWS::Serverless::RestAPI).
Originally I thought that I would use API Gateway to handle all CORS headers, so my Lambda is pure and agnostic to networking and Origin and traffic. When we integrated with our FE that is served from S3 via CloudFront, we encountered CORS problems and the only way we can find is to add following code into out Lambda handlers
resolve({
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
...accountDefinition,
}),
which explicitly couples our code with HTTP protocol and even deployment and Origin location.
Is there any way to configure this setup without forcing this code into our Lambda? I really hoped that AWS API GW is capable of shielding us from CORS and other stuff so we are not forced to couple our code with Origin and other stuff.
Upvotes: 2
Views: 288
Reputation: 2265
ApiGateway is able to handle CORS just in case you are not using proxy integration. If you are using proxy integration ApiGateway just passes what gets from lambda.
In Integration Request disable Use Lambda Proxy integration
option.
or in OpenAPI definition:
x-amazon-apigateway-integration:
type: aws # not aws_proxy
Upvotes: 0
Reputation: 116
In my experience AWS API Gateway is able to do what you need. I have done that using the following definition of the API Gateway linked to the Lambda Functions API Events
ServerlessApi:
Type: AWS::Serverless::Api
Properties:
Cors:
AllowCredentials: false
AllowHeaders: "'*'"
AllowMethods: "'*'"
AllowOrigin: "'*'"
EndpointConfiguration:
Type: REGIONAL
Name: !Ref ApiName
StageName: !Ref Environment
Adjust the CORS fields to your needs
You can see documentation of the API Gateway serverless resource here and for this resource type you can see Cors config specifically here
Once these changes are applied all of the endpoints of your API will have the CORS configs
Hope that's what you are searching for
Upvotes: 2