A developer is building a serverless application where a frontend web application, hosted on a custom domain, interacts with a backend REST API. The backend is configured using Amazon API Gateway with a Lambda proxy integration. To support cross-origin requests, the developer enabled CORS on the API Gateway resource using the AWS Console, which successfully created the OPTIONS method. However, when the frontend application attempts to send a POST request, the browser console displays a CORS error indicating that the 'Access-Control-Allow-Origin' header is missing. What must the developer do to resolve this issue?
- AIn the API Gateway console, configure the POST method's Integration Response to map the 'Access-Control-Allow-Origin' header to the client's origin.
- BConfigure the Lambda function to return a raw JSON string containing the data payload, as API Gateway automatically injects the CORS headers configured on the resource into proxy integration responses.
- Modify the Lambda function's code to return a JSON object that includes a 'headers' field containing 'Access-Control-Allow-Origin' with the appropriate origin value, alongside the 'statusCode' and 'body' fields.Answer
- DIncrease the timeout of the Lambda function to prevent the execution context from timing out during the preflight OPTIONS request, and implement connection pooling in the global scope.
Answer
Modify the Lambda function's code to return a JSON object that includes a 'headers' field containing 'Access-Control-Allow-Origin' with the appropriate origin value, alongside the 'statusCode' and 'body' fields.
In Amazon API Gateway, when using Lambda proxy integration, the backend Lambda function is responsible for returning the entire HTTP response. This response must be a JSON object containing 'statusCode', 'body', and 'headers'. To support CORS, the 'headers' object must explicitly contain the 'Access-Control-Allow-Origin' header. Enabling CORS via the API Gateway console only configures the mock integration for the preflight OPTIONS method, but does not modify the response payload returned by the Lambda function for actual HTTP methods like POST.
Step-by-Step Solution
Key Concept
API Gateway Lambda Proxy Integration CORS Requirements