A developer is troubleshooting a mobile web application hosted on https://cargo.freight-flow.io that interacts with a backend REST API. The API is hosted on Amazon API Gateway and routes requests to an AWS Lambda function using a Lambda Proxy Integration. When the application sends a POST request to create a shipment, the browser console displays a CORS preflight blocked error, and the client receives a 502 Bad Gateway error. The developer inspects the Amazon CloudWatch logs for the Lambda function and confirms that the function executed successfully and returned the following raw dictionary:
{
"message": "Shipment created successfully",
"shipmentId": "12345"
}
Which two actions should the developer take to resolve these errors?
- Configure CORS on the API Gateway resource to create an OPTIONS method that returns the required Access-Control-Allow-Origin and Access-Control-Allow-Methods headers for the preflight request.Answer
- Modify the Lambda function response to return a formatted JSON object containing statusCode, headers with Access-Control-Allow-Origin, and a stringified body.Answer
- CUpdate the CORS configuration on the Amazon S3 bucket hosting the web application to allow requests from the API Gateway endpoint.
- DModify the integration type to Lambda Custom Integration and configure a body mapping template to wrap the raw response.
- EIncrease the execution timeout of the Lambda function and enable active tracing with AWS X-Ray to debug the response serialization.
Answer
Configure CORS on the API Gateway resource to create an OPTIONS method for the preflight request, and modify the Lambda function response to return a formatted JSON object containing statusCode, headers with Access-Control-Allow-Origin, and a stringified body.
To resolve the CORS preflight blocked and 502 Bad Gateway errors, the developer must address two things. First, the OPTIONS preflight request must be handled by enabling CORS on the API Gateway resource, which configures a Mock integration to return the correct headers. Second, because the API uses a Lambda Proxy Integration, the backend Lambda function must return a properly structured JSON object that includes the statusCode, headers (including Access-Control-Allow-Origin), and a stringified JSON body. The current raw dictionary response format is not recognized by the proxy integration, resulting in a 502 Bad Gateway error.
Step-by-Step Solution
Key Concept
CORS and Lambda Proxy Integration response contracts in Amazon API Gateway.
Estimated Time:1m 30s