Soru

Zorluk: KolayTroubleshooting API Gateway Errors and CORS

A developer is building a fitness tracking web application that retrieves user statistics by calling a REST API. The API is hosted on Amazon API Gateway and uses a Lambda Proxy integration. During testing, the web browser console displays a CORS error indicating that the 'Access-Control-Allow-Origin' header is missing. The developer has already enabled CORS on the API Gateway resources using the AWS Management Console, but the error remains. Which of the following is the correct action to resolve this issue?

  1. Modify the backend Lambda function to return the Access-Control-Allow-Origin header in its response JSON.Cevap
  2. B
    Configure a CORS policy on the Amazon S3 bucket hosting the web application to allow requests from the API Gateway URL.
  3. C
    Add the Access-Control-Allow-Origin header to the API Gateway Method Response configuration and redeploy the API.
  4. D
    Create an IAM role that allows the API Gateway execution role to trust the Amazon S3 bucket hosting the application.

Cevap

Modify the backend Lambda function to return the Access-Control-Allow-Origin header in its response JSON.
Under a Lambda Proxy integration, Amazon API Gateway passes the backend response directly to the client without modifying the headers. Therefore, enabling CORS on the API Gateway resource only sets up the preflight OPTIONS endpoint. The developer must update the Lambda function code to return the Access-Control-Allow-Origin header in the headers key of the response JSON payload.

Adım Adım Çözüm

1
Determine the integration type of the API Gateway resource.
The resource is configured with Lambda Proxy integration.
Integration type dictates how requests and responses are mapped between API Gateway and the backend.
2
Understand how headers are managed in Lambda Proxy integration.
API Gateway does not modify or inject response headers for proxy integrations.
The backend Lambda function has full control over the response structure, including HTTP headers.
3
Add the required CORS header to the Lambda function's response payload.
The Lambda function returns a JSON response containing 'Access-Control-Allow-Origin' under the 'headers' key.
This satisfies the browser's origin-check validation for the client request.

Anahtar Kavram

CORS handling in API Gateway Lambda Proxy integrations
Tahmini Süre:1m 0s
Bu soruyu puanla