I followed the example from here which includes a swagger file for configuration of CORS + SAM. It seems like I still get CORS error unless I add CORS headers manually into each function:
callback(null, {
statusCode: '200',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
'Access-Control-Allow-Methods': 'OPTIONS,GET,POST,PUT,PATCH,DELETE'
},
body: JSON.stringify({message: "Hello world"})
});
Is this correct? Or am I doing something wrong?
To enable CORS for the Lambda proxy integration, you must add Access-Control-Allow-Origin:domain-name to the output headers. domain-name can be * for any domain name. Save this answer.
To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard. For more information on configuring CORS for REST APIs, see Configuring CORS for a REST API resource. For HTTP APIs, see Configuring CORS for an HTTP API.
All AWS docs suggest you need to specify those 3 headers in every API Gateway resource and return them in every function response that will support CORS
, you can see they had to add those 3 headers to the 2 API Gateway endpoints defined in the example project's swagger.yaml file.
The Github sample you mentioned is using what is called a proxy resource
in API Gateway
, which basically an API Gatewaty
route that will match any request made to the api and trigger the proxy lambda function with the request's parth, method ... etc. You can learn more about how it works here.
Are you open to trying something like serverless which can help you better organize your lambda functions just like SAM does. It also support CORS.
I know it is tedious task to add all these to your Swagger JSON for all the methods.
"headers": {
"Access-Control-Allow-Origin": {
"type": "string"
},
"Access-Control-Allow-Methods": {
"type": "string"
},
"Access-Control-Allow-Headers": {
"type": "string"
}
}
I have created a utility in Java which automatically adds these headers to your Swagger JSON. You can run it before importing it to API Gateway.
https://github.com/anandlalvb/SwaggerToAPIGateway
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