Question

Difficulty: EasyTroubleshooting API Gateway Errors and CORS

A web application hosted on a private domain attempts to submit a `PUT` request to a backend API exposed via Amazon API Gateway using a Lambda Proxy integration. The web browser blocks the request and outputs a console error indicating that the CORS preflight request failed because the 'Access-Control-Allow-Origin' header is missing. Which steps should the developer perform to resolve this issue? (Select TWO.)

  1. Define an OPTIONS method for the API Gateway resource that returns the required 'Access-Control-Allow-Origin' header.Answer
  2. Modify the Lambda function response object to include the 'Access-Control-Allow-Origin' header in its `headers` dictionary.Answer
  3. C
    Update the CORS configuration policy of the S3 bucket where the client-side code is stored to allow outgoing requests.
  4. D
    Add the 'Access-Control-Allow-Origin' header to the request headers payload inside the client application code.
  5. E
    Configure the Lambda integration as a Custom Integration rather than a Proxy Integration to enable automatic header mapping.

Answer

Define an OPTIONS method for the API Gateway resource that returns the required 'Access-Control-Allow-Origin' header, and modify the Lambda function response object to include the 'Access-Control-Allow-Origin' header in its headers dictionary.
To fix a CORS error in API Gateway when using Lambda Proxy integration, two separate adjustments are needed. First, the preflight OPTIONS request must be enabled on the API Gateway resource to respond with the 'Access-Control-Allow-Origin' header. Second, the backend Lambda function must return the 'Access-Control-Allow-Origin' header in its response JSON, because API Gateway does not inject headers into proxy responses.

Step-by-Step Solution

1
Analyze the error message and integration type.
Identified a CORS failure on an API Gateway endpoint using Lambda Proxy integration.
Since Lambda Proxy integration is used, the backend Lambda response must explicitly return the CORS headers along with the API Gateway resource preflight handling.
2
Configure the preflight OPTIONS request in API Gateway.
Created an OPTIONS method on the API Gateway resource returning the 'Access-Control-Allow-Origin' header.
This allows the browser's preflight check to succeed before initiating the actual PUT request.
3
Modify the Lambda function response.
Updated the returned JSON payload to include 'Access-Control-Allow-Origin' inside the headers block.
In proxy integrations, API Gateway does not modify the response headers, so the backend function must return them.

Key Concept

Handling CORS in API Gateway with Lambda Proxy Integration
Estimated Time:1m 30s
Rate this question