A Svelte single-page application hosted on `https://dashboard.analytics-core.org` sends an HTTP `POST` request to an Amazon API Gateway REST API. The API is configured to use a Lambda proxy integration with a backend AWS Lambda function. When the application executes the request, the web browser console displays a `502 Bad Gateway` error, followed by a CORS error stating that the `Access-Control-Allow-Origin` header is missing. The developer confirms that CORS has already been enabled on the API Gateway resource for all methods. What must the developer do to resolve this error?
- Modify the backend Lambda function to return a JSON response containing the `statusCode`, `headers`, and `body` fields, ensuring that the `headers` map includes `Access-Control-Allow-Origin` set to the application's domain.Answer
- BApply a CORS configuration policy directly to the Amazon S3 bucket hosting the Svelte application to permit cross-origin access from the API Gateway endpoint URL.
- CSwitch the integration type of the API Gateway method from Lambda proxy integration to Lambda custom integration, as proxy integrations do not support returning custom HTTP headers.
- DUpdate the API Gateway method configuration to use a custom Lambda Authorizer that explicitly allows the client application's domain within the generated IAM policy.
Answer
Modify the backend Lambda function to return a JSON response containing the `statusCode`, `headers`, and `body` fields, ensuring that the `headers` map includes `Access-Control-Allow-Origin` set to the application's domain.
The correct response resolves the root cause by ensuring the Lambda function returns the response in the exact format required by the Lambda proxy integration. Specifically, the function must return a JSON object with `statusCode`, `headers`, and `body` fields, and the `headers` field must contain the `Access-Control-Allow-Origin` header. Because the browser receives a 502 Bad Gateway when the response is malformed, it also fails the CORS preflight check since the CORS headers are not present in the error response.
Step-by-Step Solution
Key Concept
CORS handling in API Gateway Lambda Proxy Integrations