【问题标题】:AWS API Gateway deployed API can't parse request bodyAWS API Gateway 部署的 API 无法解析请求正文
【发布时间】:2020-04-16 20:25:27
【问题描述】:

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

"message": "Could not parse request body into json: Unrecognized token ....etc"

我在集成请求中尝试了这种映射{ "body" : $input.json('$') },但没有奏效。

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

{
    "description": "test description",
    "status": "test status"
}

并且请求有标头:Content-Type: application/json

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

有什么解决方案吗?

更新:

我在集成请求级别放置了一个映射模板,如下所示:

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

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

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

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

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

第二个:来自POSTMAN:

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

INFO    {
  body: 'ewogICAgImRlc2NyaXB0aW9uIjogInRlc3QiLAogICAgInByb2plY3RJZCI6IDIzLAogICAgImFjdGlvbiI6ICJ0ZXN0IiwKICAgICJlbnRpdHkiOiAidGVzdCIsCiAgICAic3RhcnREYXRlIjogIjAxLTAxLTIwMjAiLAogICAgImVuZERhdGUiOiAiMDEtMDEtMjAyMCIKfQ=='
}

这表明在使用 POSTMAN 发出请求的情况下,JSON 有效负载会自动进行字符串化。什么会导致这样的事情?以及如何处理?

【问题讨论】:

  • 评论不用于扩展讨论;这个对话是moved to chat
  • 能否也分享一下CloudFormation模板的yaml/json相关的sn-p?

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


【解决方案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:
- '*/*'

【讨论】:

  • @m.y.m 如果有任何不准确之处或您为解决问题而采取的不同措施,请更正答案。
【解决方案2】:

您需要在响应中添加自定义标头才能正确响应。

  // 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)
  };

【讨论】:

    猜你喜欢
    • 2016-01-30
    • 2016-12-14
    • 2016-02-07
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-18
    • 2022-10-14
    相关资源
    最近更新 更多