javascript - 从 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 格式的请求正文?
解决方案
这是对的。默认 lambda 集成是通过绕过 API Gateway 的请求/响应转换器的“lambda 代理”。你基本上得到了原始的有效载荷来处理。
如果您希望 API Gateway 做一些工作,您需要切换集成lambda
并将 API Gateway 配置为接受application/json
作为请求类型。
https://serverless.com/framework/docs/providers/aws/events/apigateway#lambda-integration
推荐阅读
- php - 以编程方式发送 Ninja Forms 通知
- mysql - mysqli 查询带有编码的多个案例
- c# - 如何禁用恢复 Visual Studio 安装程序项目的丢失文件?
- php - 替换数组键并用它们移动值
- mysql - 如何仅对具有正支付总额的记录进行分组?
- json - 如何正确将 JSON 导入 Excel
- kubernetes - Kubernetes - 在容器之间共享单个文件(在同一个 pod 内)
- powerbi - 计算 RELADTABLE 的 MAX
- php - 如何在使用 $this 和短代码类时在函数中返回函数
- python - 如何根据其他数据框过滤一个熊猫数据框日期