【问题标题】:Why is my response coming in multiple messages? How can I fix it?为什么我的回复出现在多条消息中?我该如何解决?
【发布时间】: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


【解决方案1】:

更大的响应以块的形式发送。因此,您需要在收到所有块后收集它们并加入它们。 'data' 事件在你接收到一个块时被调度,而'end' 事件在你接收到所有块时被调度。

来自nodejs docs的一个简短示例

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

【讨论】:

    猜你喜欢
    • 2020-09-14
    • 2021-05-21
    • 2018-01-18
    • 2019-12-22
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多