AWS Lambda,API Gateway返回格式错误的Lambda代理响应,502错误

时间:2017-05-05 16:35:00

标签: node.js amazon-web-services aws-lambda aws-api-gateway

经过大量的谷歌搜索和几个小时的试验和错误后,我无法找到为什么我收到此错误消息:

  

由于配置错误导致执行失败:格式错误的Lambda代理响应

当我使用测试lambda功能运行lambda时,它工作正常。 对此类似问题的回答表明lambda的响应需要满足这种格式:

{
  "isBase64Encoded": true|false,
  "statusCode": httpStatusCode,
  "headers": { "headerName": "headerValue", ... },
  "body": "..."
}

以下是我正在使用的lambda(符合此格式):

'use strict';

var aws = require('aws-sdk');
var ses = new aws.SES();

var RECEIVER = "XXXX@XXXX.com";
var SENDER = "XXXX@XXXX.com";

const response_success = {
      'isBase64Encoded': false,
      'statusCode': 200,
      'headers': {
          'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        message: 'ok'
      }),
};

const response_error = {
    'isBase64Encoded': false,
    'statusCode': 400,
    'headers': {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        message: 'error'
    }),
};

exports.handler = (event, context, callback) => {
    sendEmail(event, function(error, data) {
        if (error) {
           callback(response_error);
        } else {
           callback(null, response_success);
        }
    });
};

function sendEmail(event, done) {
    var params = {
        Destination: {
            ToAddresses: [
                RECEIVER
            ]
        },
        Message: {
            Body: {
                Text: {
                    Data: event.message,
                    Charset: 'UTF-8'
                }
            },
            Subject: {
                Data: 'Lamda Test Email',
                Charset: 'UTF-8'
            }
        },
        Source: SENDER
    }
    ses.sendEmail(params, done);
}

我不认为这是一个配置问题,而且我正在使用Terraform构建基础架构,如果这有任何帮助的话。 提前谢谢!

编辑:(添加了以下错误日志)

Execution log for request test-request
Fri May 05 16:36:22 UTC 2017 : Starting execution for request: test-invoke-request
Fri May 05 16:36:22 UTC 2017 : HTTP Method: POST, Resource Path: /messages
Fri May 05 16:36:22 UTC 2017 : Method request path: {}
Fri May 05 16:36:22 UTC 2017 : Method request query string: {}
Fri May 05 16:36:22 UTC 2017 : Method request headers: {}
Fri May 05 16:36:22 UTC 2017 : Method request body before transformations: { "message" : "test" }
Fri May 05 16:36:22 UTC 2017 : Endpoint request URI: https://lambda.eu-west-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:eu-west-1:670603659598:function:mailer_lambda/invocations
Fri May 05 16:36:22 UTC 2017 : Endpoint request headers: {x-amzn-lambda-integration-tag=test-request, Authorization=****************************************************************************************************************************************************************************************************************************************************************************************************************************************cd4bef, X-Amz-Date=20170505T163622Z, x-amzn-apigateway-api-id=jnnd4wh3f8, X-Amz-Source-Arn=arn:aws:execute-api:eu-west-1:670603659598:jnnd4wh3f8/null/POST/messages, Accept=application/json, User-Agent=AmazonAPIGateway_jnnd4wh3f8, X-Amz-Security-Token=FQoDYXdzEPH//////////wEaDB1y8s+RanRAP61EAyK3A1f/o2BrYfqUOQwsrn7bRF6OMmeD3Se+WVWA1reC3tZZ6+IfnFa0LVNnaaNM27o/Vqc/m4tnQR5xUACK3I6ssbkwHj9E4sM3sQ4L+zNQSnkZhMAIRxbyxHJRp1E9/8XnVxRJAWF5ynWCmDxe2tQQ8SXCnQKIKzJypIgp0E0BD3hZ92soW6wID64uaufk+qYXiV7AJxd+Z9Gg1TyiwacUA2i0g4xsjDqeAA5wFbI9KoiYK6/+uwpQ5mxdxg6JIxS7H9jULRRn7V9E4YVXsXCWXh8RXqGmigGzWXChYAD3S7b9rBLUpTga3t3SlnnK [TRUNCATED]
Fri May 05 16:36:22 UTC 2017 : Endpoint request body after transformations: {"resource":"/messages","path":"/messages","httpMethod":"POST","headers":null,"queryStringParameters":null,"pathParameters":null,"stageVariables":null,"requestContext":{"accountId":"670603659598","resourceId":"90rzx3","stage":"test-invoke-stage","requestId":"test-invoke-request","identity":{"cognitoIdentityPoolId":null,"accountId":"670603659598","cognitoIdentityId":null,"caller":"670603659598","apiKey":"test-invoke-api-key","sourceIp":"test-invoke-source-ip","accessKey":"ASIAJA3SYDRPGE36PMXQ","cognitoAuthenticationType":null,"cognitoAuthenticationProvider":null,"userArn":"arn:aws:iam::670603659598:root","userAgent":"Apache-HttpClient/4.5.x (Java/1.8.0_112)","user":"670603659598"},"resourcePath":"/messages","httpMethod":"POST","apiId":"jnnd4wh3f8"},"body":"{ \"message\" : \"test\" }","isBase64Encoded":false}
Fri May 05 16:36:22 UTC 2017 : Endpoint response body before transformations: {"errorMessage":"[object Object]"}
Fri May 05 16:36:22 UTC 2017 : Endpoint response headers: {x-amzn-Remapped-Content-Length=0, x-amzn-RequestId=f91382de-31b0-11e7-bfaa-c7e2e3193355, Connection=keep-alive, Content-Length=34, X-Amz-Function-Error=Handled, Date=Fri, 05 May 2017 16:36:22 GMT, X-Amzn-Trace-Id=root=1-590caa06-47c0526e9aba46d52e47aee5;sampled=0, Content-Type=application/json}
Fri May 05 16:36:22 UTC 2017 : Execution failed due to configuration error: Malformed Lambda proxy response
Fri May 05 16:36:22 UTC 2017 : Method completed with status: 502

2 个答案:

答案 0 :(得分:4)

感谢@johni和@UXDart的帮助。问题是api网关和lambda之间的集成请求正在改变请求体(你可以找到关于这个here的更多信息)

所以我更改了处理程序以解析event.body,所以我现在可以从事件中访问正确的数据。 (N.B在lambda中对此进行测试会导致函数超时,因此您需要从api-gateway进行测试)

以下是我改变的内容:

exports.handler = (event, context, callback) => {
    const body = JSON.parse(event.body);

    sendEmail(body, function(error, data) {
        if (error) {
           callback(null, response_error);
        } else {
           callback(null, response_success);
        }
    });
};

答案 1 :(得分:1)

不完全确定,但是你应该只返回一个结果,即使是错误,因为你使用的是状态码

所以改变回调(response_error);回调(null,response_error);