A client-side single-page dashboard application hosted on `https://internal-app.net` sends a `DELETE` request to a backend API. The API is hosted on Amazon API Gateway and integrated with a backend AWS Lambda function using a Lambda proxy integration. During testing, the browser console shows that the `DELETE` request is blocked due to a missing CORS header during the preflight check. Furthermore, direct invocations of the endpoint using a command-line tool result in a `502 Bad Gateway` error with the message 'Malformatted Lambda proxy response' in the CloudWatch logs. Which two actions must the developer take to resolve both the CORS preflight block and the integration error?
- Enable CORS on the API Gateway resource to create an OPTIONS method that returns the required Access-Control-Allow-Methods and Access-Control-Allow-Origin headers.Answer
- Modify the backend Lambda function's return payload to be a JSON object containing the statusCode integer, a headers object with the Access-Control-Allow-Origin header, and a stringified body.Answer
- CAdd the Access-Control-Allow-Origin header to the CORS configuration of the Amazon S3 bucket where the frontend dashboard application is hosted.
- DConfigure an Integration Response mapping template in API Gateway to transform the Lambda function's raw output string into a structured JSON response.
- EConfigure a Lambda authorizer on the API Gateway method to validate the Origin header and return an IAM policy allowing the execute-api:Invoke action.
Answer
Enable CORS on the API Gateway resource to create an OPTIONS method that returns the required Access-Control-Allow-Methods and Access-Control-Allow-Origin headers, and modify the backend Lambda function's return payload to be a JSON object containing the statusCode integer, a headers object with the Access-Control-Allow-Origin header, and a stringified body.
The correct options resolve both issues: first, enabling CORS on the API Gateway resource creates the OPTIONS method to handle the browser's preflight request; second, formatting the Lambda response as a JSON object with statusCode, headers (including the CORS header), and body complies with Lambda proxy integration rules and resolves the 502 Bad Gateway error.
Step-by-Step Solution
Key Concept
API Gateway Lambda proxy integrations require both a preflight OPTIONS method configured at the API Gateway level and a properly formatted JSON response containing the status code, headers (including CORS headers), and body returned directly from the Lambda function.
Estimated Time:2m 0s