Soru

Zorluk: OrtaTroubleshooting API Gateway Errors and CORS

A client-side Next.js web portal hosted on https://portal.ecocharge.net sends a POST request to an Amazon API Gateway REST API configured with a Lambda Proxy integration to register new users. The API Gateway has CORS enabled on the resource. The web portal console shows a CORS error stating that the 'Access-Control-Allow-Origin' header is missing on the requested resource after the browser successfully completes the OPTIONS preflight request. Which of the following is the correct action to resolve this issue?

  1. A
    Configure a custom Lambda Authorizer for the POST method and configure the authorizer's response payload to include the Access-Control-Allow-Origin header.
  2. B
    Configure a CORS policy on the Amazon S3 bucket hosting the web portal's static assets to allow incoming traffic from the API Gateway endpoint.
  3. Modify the backend Lambda function's response to return a JSON object containing a 'headers' key with the 'Access-Control-Allow-Origin' header.Cevap
  4. D
    Modify the Lambda function to return a plain text response body, and configure API Gateway's Integration Response to map the CORS headers.

Cevap

Modify the backend Lambda function's response to return a JSON object containing a 'headers' key with the 'Access-Control-Allow-Origin' header.
For a Lambda Proxy integration in Amazon API Gateway, the backend Lambda function is responsible for returning the complete response structure, including the status code, body, and all HTTP headers. While enabling CORS in the API Gateway console configures the preflight OPTIONS method, the actual method response (such as the POST response) must return the 'Access-Control-Allow-Origin' header directly within the Lambda function's JSON response payload.

Adım Adım Çözüm

1
Analyze the integration type configured on the API Gateway resource.
The resource uses Lambda Proxy integration.
Lambda Proxy integration requires the backend Lambda function to format its output as a specific JSON object containing status code, headers, and body.
2
Determine where the CORS headers must be added.
Since API Gateway CORS enabling only sets headers on the OPTIONS preflight method automatically, the actual method (POST) must return the CORS headers from the integration backend.
For Lambda Proxy integrations, API Gateway does not evaluate or inject headers for integration responses on non-OPTIONS methods.
3
Update the Lambda function's output dictionary format.
The Lambda function returns a payload containing: { 'statusCode': 200, 'headers': { 'Access-Control-Allow-Origin': '*' }, 'body': '...' }
This structural output satisfies the Lambda Proxy integration contract and includes the required CORS headers for the browser to accept the request.

Anahtar Kavram

Lambda Proxy Integration CORS Requirements
Tahmini Süre:1m 30s
Bu soruyu puanla