Question

Difficulty: EasyTroubleshooting API Gateway Errors and CORS

A developer is hosting a single-page web application in an Amazon S3 bucket. The application makes API calls to an Amazon API Gateway endpoint that is integrated with a Lambda function using Lambda Proxy integration. During testing, the browser console displays a CORS error stating that the preflight request was blocked because the Access-Control-Allow-Origin header is missing. Which two steps must the developer take to resolve this CORS error? (Select TWO.)

  1. Configure the API Gateway resource to handle the preflight OPTIONS request and return the Access-Control-Allow-Origin header.Answer
  2. Modify the backend Lambda function to include the Access-Control-Allow-Origin header in its response JSON object.Answer
  3. C
    Configure a CORS policy on the Amazon S3 bucket hosting the frontend application to allow requests from the API Gateway endpoint.
  4. D
    Change the Lambda function to return a plain text string with the headers instead of a structured JSON response.
  5. E
    Deploy a custom Lambda authorizer to generate and inject the Access-Control-Allow-Origin header into the client request.

Answer

Configure the API Gateway resource to handle the preflight OPTIONS request and modify the backend Lambda function to include the Access-Control-Allow-Origin header in its response JSON object.
To resolve CORS errors when using Amazon API Gateway with Lambda Proxy integration, two actions are required: enabling CORS on the API Gateway resource to handle the OPTIONS preflight request, and modifying the backend Lambda function to return the Access-Control-Allow-Origin header in its response JSON object.

Step-by-Step Solution

1
Identify the source of the preflight failure.
Recognize that the browser initiates an OPTIONS preflight request before sending the actual API request.
Before sending non-simple HTTP requests, browsers perform preflight checks to verify allowed origins.
2
Configure the OPTIONS method response in API Gateway.
Enable CORS on the API Gateway resource to return the Access-Control-Allow-Origin header for the preflight OPTIONS request.
This satisfies the browser's preflight requirements.
3
Configure the backend response headers.
Update the Lambda function's JSON payload response to include 'Access-Control-Allow-Origin' under the 'headers' object.
For Lambda Proxy integrations, API Gateway does not modify the backend response, requiring the Lambda function to supply the CORS header directly.

Key Concept

Cross-Origin Resource Sharing (CORS) resolution in API Gateway Lambda Proxy integrations requires both the preflight OPTIONS response from API Gateway and the custom origin headers returned by the Lambda function.
Estimated Time:1m 0s
Rate this question