AWS API Gateway always returns 502 bad gateway

微笑、不失礼 提交于 2021-02-08 09:54:09

问题


I have created a simple lambda function in AWS that returns list from DynamoDB. I have also created API Gateway to trigger the lambda function. The function works fine when I test in AWS console. But I always get 502 bad gateway below error when I test this function in Postman. ({ "message": "Internal server error" }

Below is the function in node.js:

const doc = require('dynamodb-doc');

const dynamo = new doc.DynamoDB();

/**
 * Provide an event that contains the following keys:
 *
 *   - operation: one of the operations in the switch statement below
 *   - tableName: required for operations that interact with DynamoDB
 *   - payload: a parameter to pass to the operation being performed
 */
exports.handler = async (event) => {

    const operation = event.operation;
    const payload = event.payload;

    if (event.tableName) {
        payload.TableName = event.tableName;
    }

    switch (operation) {
        case 'create':
            return await dynamo.putItem(payload).promise();
        case 'read':
            return await dynamo.getItem(payload).promise();
        case 'update':
            return await dynamo.updateItem(payload).promise();
        case 'delete':
            return await dynamo.deleteItem(payload).promise();
        case 'list':
            return await dynamo.scan(payload).promise();
        case 'echo':
            return payload;
        case 'ping':
            return 'pong';
        default:
            throw new Error(`Unrecognized operation "${operation}"`);
    }
};

Below is generated API Gateway Endpoint details.

API endpoint: https://iabzqisam7.execute-api.us-east-1.amazonaws.com/test/moneyAppDynamoDBOperationsLambda
Authorization: NONE
Method: ANY
Resource path: /moneyAppDynamoDBOperationsLambda
Stage: test

Here is how I am trying to test API using Postman:

 Postman  URL(Get) : https://iabzqisam7.execute-api.us-east-1.amazonaws.com/test/moneyAppDynamoDBOperationsLambda

    Headers: Key: content-type, Value: application/json
    Body (raw) :
    {
        "operation": "list",
        "tableName": "Advertiser",
        "payload": {
            "TableName": "Advertiser"
        }
    }

It works perfectly fine within AWS console.

Any idea why I am keep getting 502 bad gateway error while calling API Gateway from Postman ?


回答1:


502 Bad Gateway Exception, usually for an incompatible output returned from a Lambda proxy integration backend and occasionally for out-of-order invocations due to heavy loads.

API getway output will not tell you that the problem is related to a Lambda error or API getway or policy issue .

The API Gateway returned a 502 which means that it didn’t understand the output returned by Lambda and give you {“message”: “Internal server error”} 502.

Debug using enable logging on API getway

Create new IAM role to allow API Gateway to push logs to CloudWatch. Attached following policy attach:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:DescribeLogGroups",
                "logs:DescribeLogStreams",
                "logs:PutLogEvents",
                "logs:GetLogEvents",
                "logs:FilterLogEvents"
            ],
            "Resource": "*"
        }
    ]
}

Trust policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "apigateway.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

In API Gateway console -->Go to settings -> Add ARN of the API Gateway-CloudWatch logging role--> 'Save'

Go to the stage of your API. Under 'CloudWatch Settings', select 'Enable CloudWatch Logs'. Set 'Log level' to 'INFO'. Select 'Log full requests/responses data'.

Plesae check log and share error logs in question .

  • How can I see AWS Gateway logs for external calls?

    Output Format of a Lambda Function for Proxy Integration

If the function output is of a different format or malformed , API Gateway returns a 502 Bad Gateway error response .

  • https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
  • https://aws.amazon.com/premiumsupport/knowledge-center/malformed-502-api-gateway/.


来源:https://stackoverflow.com/questions/55481238/aws-api-gateway-always-returns-502-bad-gateway

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!