AWS API Gateway部署的API无法解析请求正文

时间:2019-12-26 16:36:20

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

我有一个与API Gateway集成的Lambda函数,并且该堆栈已部署为云形成模板。当我尝试在AWS Web控制台中测试终结点时,我得到了正确的响应,但是当我尝试调用API的已部署版本时,却出现了该错误。

import { Ionicons } from '@expo/vector-icons';

我在集成请求中尝试了此映射"message": "Could not parse request body into json: Unrecognized token ....etc" ,但是没有用。

这是我尝试使用POSTMAN发送的JSON

{ "body" : $input.json('$') }

并且请求具有标头:{ "description": "test description", "status": "test status" }

这是POSTMAN请求正文和标头以及来自API的响应的屏幕截图:

enter image description here enter image description here

有解决方案的人吗?

更新:

我将映射模板放在集成请求级别,如下所示:

Content-Type: application/json

并更新了lambda函数以记录即将到来的请求,然后发出了2个请求:

第一个:从API Gateway测试Web控制台:

我在cloudwatch日志中发现了以下内容:

{
   "body-json" : $input.json('$')
}

第二个:来自POSTMAN:

我在cloudwatch日志中发现了以下内容:

INFO    {
  body: {
    description: 'test',
    projectId: 23,
    action: 'test',
    entity: 'test',
    startDate: '01-01-2020',
    endDate: '01-01-2020'
  }
}

这表示在使用POSTMAN进行请求的情况下,JSON有效负载会自动进行字符串化。什么会引起这种事情?以及如何处理?

2 个答案:

答案 0 :(得分:1)

在这种情况下,由于我们没有使用代理集成,因此需要编辑映射模板。

"body-json" : $input.json('$')
//also if binary data type is enabled for your api your body will be a base64
//encoded string which could be decoded using
$util.base64Decode($input.json('$'))

还可能默认启用二进制数据类型,请在SAM模板中搜索这些数据

x-amazon-apigateway-binary-media-types:
- '*/*'

答案 1 :(得分:0)

您需要在响应中添加一个自定义标头,以使其正确响应。

  // The output from a Lambda proxy integration must be 
  // in the following JSON object. The 'headers' property 
  // is for custom response headers in addition to standard 
  // ones. The 'body' property  must be a JSON string. For 
  // base64-encoded payload, you must also set the 'isBase64Encoded'
  // property to 'true'.
  let response = {
      statusCode: responseCode,
      headers: {
          "x-custom-header" : "my custom header value"
      },
      body: JSON.stringify(responseBody)
  };