【发布时间】:2020-07-15 00:04:01
【问题描述】:
我有一个 Firebase 函数,我试图在其中使用第 3 方 API。如果我的反应很短,它会立即返回,一切正常。但是,当我的回复太长时,它会分成两部分回来。这会导致我的 JSON 解析失败。
import * as https from 'https';
export function search(searchTerm: string): Promise<IResponse> {
return new Promise<IResponse>((resolve, reject) => {
const options =
{
hostname: hostname,
port: port,
path: 'search?query=' + searchTerm,
method: 'GET',
headers:
{
'x-app-id': appID,
'x-app-key': appKey
}
};
const request = https.request(options, (response) => {
response.on('data', (data) => {
const json = data.toString('utf8');
//1. This prints out
//3. This prints out again (after the JSON parsing fails)
console.log(json);
//2. This fails "SyntaxError: Unexpected end of JSON input"
resolve(convertToResponse(json));
});
});
request.end();
});
}
我做错了什么?我该如何解决?
【问题讨论】:
-
不使用“request”模块,而是使用“request-promise”在一个缓冲区中获取整个响应。此外,它将大大简化您的代码。或者,这些更现代的库之一:github.com/request/request/issues/3143
-
@DougStevenson 谢谢,但我没有使用请求模块。
-
无论如何,如果您使用更现代的替代方案,可以让您承诺使用而不是回调,您将节省大量精力。
标签: node.js typescript firebase google-cloud-functions