首页 > 解决方案 > 从 API 网关获取请求正文作为字符串,期望 JSON 内容

问题描述

我最近开始创建一个用于学习目的的 slack slash 命令机器人。我从 EC2 服务器上的 API 网关和 nodejs 应用程序获取不同格式的请求正文。我只想从 API 网关获取 JSON 格式的请求正文。怎么能得到?

让我们看一下正文格式和 serverless.yml 文件。

首先,我安装了无服务器框架并使用以下代码创建了 serverless.yml 文件,

service: as-serverless-slack-bot 
# NOTE: update this with your service name

# You can pin your service to only deploy with a specific Serverless version
# Check out our docs for more details
# frameworkVersion: "=X.X.X"

provider:
  name: aws
  runtime: nodejs8.10

 functions:
 info:
    handler: handler.info
    events:
      - http:
          method: post
          path: slack/info
          cors: true

现在,我已经成功部署了它。但是,当我执行 slack slash 命令时,我从 API 网关接收到字符串格式的请求正文,

body: 'token=XXXXXX&team_id=XXXXXXXX&team_domain=XXXXXXX&channel_id=XXXXXXX&channel_name=XXXXXX&user_id=XXXXXX&user_name=XXXXXXX&command=%2Finfo&text=about+users&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2XXXXXXX%2XXXXXXXXXXX&trigger_id=562173962614.55XXXXXXXXX.326e28e8599XXXcacf0XXXXXa'

同时,对于相同的操作,我在 EC2 nodejs 应用程序中获取 JSON 格式的请求正文。

{
  "body": {
    "token": "xxxxxxxxx",
    "team_id": "xxxxxx",
    "team_domain": "xxxxxx",
    "channel_id": "xxxx",
    "channel_name": "xxxx",
    "user_id": "xxx",
    "user_name": "xx",
    "command": "/info",
    "text": "about users",
    "response_url": "https://hooks.slack.com/commands/x/x/x",
    "trigger_id": "560161450593.558xxxxxxxx3.3741c456xxxxx05cc6xxx62"
  }
}

那么,如何从 API 网关获取 JSON 格式的请求正文?

标签: javascriptaws-api-gatewayserverless-frameworkserverless

解决方案


这是对的。默认 lambda 集成是通过绕过 API Gateway 的请求/响应转换器的“lambda 代理”。你基本上得到了原始的有效载荷来处理。

如果您希望 API Gateway 做一些工作,您需要切换集成lambda并将 API Gateway 配置为接受application/json作为请求类型。

https://serverless.com/framework/docs/providers/aws/events/apigateway#lambda-integration


推荐阅读