AWS API Gateway和lamda-如何获取event.body

时间:2019-03-20 08:27:46

标签: amazon-web-services aws-lambda aws-api-gateway

我是aws的新手,但我有一个奇怪的问题,无法在lamda处理程序函数中获取事件的正文。

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        body: event.body
    };
    return response;
};

enter image description here

我进行测试时会得到

Response:
{
  "statusCode": 200
}

但是当我只返回事件时

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        body: event <=====
    };
    return response;
};

我明白了

Response:
{
  "statusCode": 200,
  "body": {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
  }
}

我正在使用节点8.10。有人知道我在做什么错吗?

2 个答案:

答案 0 :(得分:1)

Lambda控制台中的测试事件正是通过Lambda处理程序中的event参数获得的。当您放置{"a":1}时,您会得到{"a":1}

您可以从组合框中选择一个模板来模拟不同类型的AWS服务事件(SNS,S3,API网关)。

当您返回HTTP响应时,您可能想模拟一个API网关事件,它看起来可能像这样:

{
  "body": "{\"a\":1}",
  "pathParameters": {
    "id": "XXX"
  },
  "resource": "/myres",
  "path": "/myres",
  "httpMethod": "GET",
  "isBase64Encoded": true,
  "requestContext": {
    "authorizer": {
      "tenantId": "TEST"
    },
    "accountId": "123456789012",
    "resourceId": "123456",
    "stage": "test",
    "requestId": "test-request-id",
    "requestTime": "09/Apr/2015:12:34:56 +0000",
    "requestTimeEpoch": 1428582896000,
    "path": "/myres",
    "resourcePath": "/myres,
    "httpMethod": "GET",
    "apiId": "1234567890",
    "protocol": "HTTP/1.1"
  }
}

然后您将在event.body中将主体作为JSON字符串-您可以通过JSON.parse(event.body)将其转换为对象。

返回时,您必须使用JSON.stringify序列化响应正文:

return {
    statusCode: 200,
    body: JSON.stingify({your:'object'})
};

答案 1 :(得分:0)

更改

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        body: event.body
    };
    return response;
};

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        body: JSON.stringify(event.body)
    };
    return response;
};

您在API网关中返回的正文必须经过字符串化处理,否则它将不知道如何处理响应。