【发布时间】:2019-08-14 15:12:17
【问题描述】:
我们有一个公司 API,目前正在切换到 AWS API Gateway。 API Gateway 中的端点使用 Node.js Lambda 函数来访问我们现有的内部端点,使用 AWS 进行速率限制和身份验证。我的第一个端点运行良好,但我的第二个端点给了我一个空白响应,并且在 CloudWatch 中我看到以下错误:
2017-10-04T03:24:46.957Z 925a40ba-a8b3-11e7-be24-8d954fcaf057
SyntaxError: Unexpected end of JSON input
at Object.parse (native)
at IncomingMessage.<anonymous> (/var/task/index.js:67:37)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
如果我直接点击我们的 API,它会正确返回有效的 JSON
[{"name":"Distinct Zips","offers":8,"affiliates":1,"margin":0,"profit":0,"paid":0,"received":0,"conversion_rate":100,"average_profit":0,"total_calls":1,"qualified_calls":1,"duplicate_calls":0,"returned_calls":0},{"name":"","offers":0,"affiliates":0,"margin":0,"profit":0,"paid":0,"received":0,"conversion_rate":0,"average_profit":0,"total_calls":0,"qualified_calls":0,"duplicate_calls":0,"returned_calls":0},{"name":"Total","offers":8,"affiliates":1,"margin":0,"profit":0,"paid":0,"received":0,"conversion_rate":100,"average_profit":0,"total_calls":1,"qualified_calls":1,"duplicate_calls":0,"returned_calls":0}]
JSON 是有效的,所以我不确定 AWS 为何返回意外结束的错误。我尝试将结果更改为单个 JSON 项,而不是数组,但在 CloudWatch 中仍然出现相同的错误。我什至不确定从哪里开始寻找,是否可能与我们的 Lambda 函数有关,或者是否与我们的代码库实际返回的内容有关。
为清晰起见进行编辑
请求使用 Lambda 函数集成,但不使用 Lambda 代理集成。完整的 lambda 可以在 https://gist.github.com/awestover89/a53c0f2811c566c902a473ea22e825a5
看到我们使用回调在 Lambda 中处理分块数据:
callback = function(response) {
var responseString = '';
// Another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
responseString += chunk;
});
// The whole response has been received
response.on('end', function () {
console.log(responseString);
// Parse response to json
var jsonResponse = JSON.parse(responseString);
var output = {
status: response.statusCode,
bodyJson: jsonResponse,
headers: response.headers
};
【问题讨论】:
-
APIGateway 是如何配置的?在“集成请求”部分下,您是否选择了“Lambda 函数”和“使用 Lambda 代理集成”,所以它会直接传递所有内容?
-
console.logevent在您的处理程序中,然后检查 CloudWatch 日志。用你看到的更新你的问题。 -
听起来您正在使用 http/https 从后端获取响应,并且您捕获响应的方式可能存在问题,导致您只解析第一块数据而不是而不是等待整个响应,因此代码以与响应的块到达的大小或时间相关的方式失败。
console.log(foo)就在你之前JSON.parse(foo)?即 Lambda 问题而不是实际的 API Gateway 问题。 -
我们不使用 Lambda 代理集成,我已经用 Lambda 函数的要点更新了问题。 JSON.parse 之前的响应的 console.log 在 CloudWatch 中只有一个空字符串。
-
我想我找到了问题,查询字符串没有正确发送到我们的直接端点,这导致结果返回格式错误(需要查询字符串参数)
标签: node.js amazon-web-services aws-api-gateway