我目前正在使用 NodeJS 通过 AWS Api Gateway 在 AWS lambda 上构建机器人,但遇到了 POST 请求和 JSON 数据的问题。我的 api 使用“使用 Lambda 代理集成”,甚至当我测试代理发送 Application/json 内容类型和正文中的一些 json 时,例如 {"foo":"bar"}
我可以不首先解析对象就不能访问该对象
例如
var json = JSON.parse(event.body);
console.log(json.foo);
现在我知道,仅通过 JSON.parse 运行它似乎没什么大不了的,但我见过许多其他示例,但情况根本不是这样。看到这里https://github.com/pinzler/fb-messenger-bot-aws-lambda/blob/master/index.js
我需要向 API 网关添加任何内容才能正确处理此问题吗?我的“发布方法请求”部分中的“请求正文”步骤为请求正文设置了 application/json 的内容类型。
据我所知,上面示例的自述文件似乎没有使用代理集成,所以我不确定我应该在这里做什么
最佳答案
您可以在 API Gateway 中配置两种不同的 Lambda 集成:
对于 Lambda 非代理集成,您可以自定义要在负载中传递给 Lambda 的内容,无需解析正文,但当您使用 API Gateway 中的 Lambda 代理集成,API Gateway 将在负载中将所有内容代理给 Lambda,如下所示:
{
"message": "Hello me!",
"input": {
"path": "/test/hello",
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, lzma, sdch, br",
"Accept-Language": "en-US,en;q=0.8",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Host": "wt6mne2s9k.execute-api.us-west-2.amazonaws.com",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
"Via": "1.1 fb7cca60f0ecd82ce07790c9c5eef16c.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "nBsWBOrSHMgnaROZJK1wGCZ9PcRcSpq_oSXZNQwQ10OTZL4cimZo3g==",
"X-Forwarded-For": "192.168.100.1, 192.168.1.1",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"pathParameters": {"proxy": "hello"},
"requestContext": {
"accountId": "123456789012",
"resourceId": "us4z18",
"stage": "test",
"requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
"identity": {
"cognitoIdentityPoolId": "",
"accountId": "",
"cognitoIdentityId": "",
"caller": "",
"apiKey": "",
"sourceIp": "192.168.100.1",
"cognitoAuthenticationType": "",
"cognitoAuthenticationProvider": "",
"userArn": "",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
"user": ""
},
"resourcePath": "/{proxy+}",
"httpMethod": "GET",
"apiId": "wt6mne2s9k"
},
"resource": "/{proxy+}",
"httpMethod": "GET",
"queryStringParameters": {"name": "me"},
"stageVariables": {"stageVarName": "stageVarValue"},
"body": "{\"foo\":\"bar\"}",
"isBase64Encoded": false
}
}
对于您引用的示例,它没有从原始请求中获取正文。它正在构建返回 API 网关的响应正文。它应该是这样的格式:
{
"statusCode": httpStatusCode,
"headers": { "headerName": "headerValue", ... },
"body": "...",
"isBase64Encoded": false
}
关于amazon-web-services - 通过API网关在aws Lambda中获取json正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41648467/