访问lambda REST时格式错误的Lambda代理响应

时间:2018-05-11 21:52:13

标签: javascript aws-lambda serverless-framework

我使用Javascript创建将部署在AWS Lambda上并用作REST的简单函数。

它应该生成随机名称,但现在我使用硬编码值。

// NamingService.js
class NamingService {
    generateName() {
        return 'generated-name'
    }
}

module.exports = NamingService;

在此文件中我处理请求

const NamingService = require('./NamingService');

const responses = {
    success: (data={}) => {
        return {
            "statusCode": 200,
            "headers": {
                "Access-Control-Allow-Origin" : "*",
                "Access-Control-Allow-Credentials" : true
            },
            "body": JSON.stringify(data)
        }
    },
    error: (error) => {
        return {
            "statusCode": error.code || 500,
            "headers": {
                "Access-Control-Allow-Origin" : "*",
                "Access-Control-Allow-Credentials" : true
            },
            "body": JSON.stringify(error)
        }
    }
};

module.exports = {
    generateName: (event, context, callback) => {
        context.callbackWaitsForEmptyEventLoop = false;
        const namingService = new NamingService();
        namingService.generateName()
            .then(name => {
                callback(null, responses.success(name))
            })
            .catch(error => {
                callback(null, responses.error(error))
            })
    }
};

我使用serverless来部署lambda函数

service: naming-service

provider:
  name: aws
  runtime: nodejs8.10
  region: eu-west-1
  memorySize: 128
  timeout: 30

functions:
  generateName:
    handler: lambdaHandlers.generateName
    events:
      - http:
          path: jester/name/generate
          method: get
          cors:
            origins:
              - '*'

serverless deploy后,它显示了回复

region: eu-west-1
stack: naming-service-dev
api keys:
  None
endpoints:
  GET - https://endpoint/jester/name/generate
functions:
  generateName: naming-service-dev-generateName

但是当我尝试运行它时(在API网关上使用测试)我得到了这个错误

Fri May 11 21:37:19 UTC 2018 : Endpoint response body before transformations: "generated-name"
Fri May 11 21:37:19 UTC 2018 : Endpoint response headers: {Content-Length=16, Date=Fri, 11 May 2018 21:37:19 GMT;sampled=0, Content-Type=application/json}
Fri May 11 21:37:19 UTC 2018 : Execution failed due to configuration error: Malformed Lambda proxy response
Fri May 11 21:37:19 UTC 2018 : Method completed with status: 502

有什么问题?

1 个答案:

答案 0 :(得分:0)

问题在于generateName处理程序。我不应该在方法then

上使用generateName
generateName: (event, context, callback) => {
    context.callbackWaitsForEmptyEventLoop = false;
    const namingService = new NamingService();
    const generatedName = namingService.generateName();
    callback(null, responses.success(generatedName));
}