【问题标题】:Handling status >= 400 in streamed node.js request http client在流式 node.js 请求 http 客户端中处理状态 >= 400
【发布时间】:2018-03-07 23:14:16
【问题描述】:

我正在使用 https://github.com/request/request 发出 HTTP 请求,并且我想接收 JSON。响应会非常大,所以我想使用流方法来处理响应。但是,我正在调用的 API 返回状态 >= 400 的“文本/纯文本”,这意味着我的 JSONStream 将失败。代码:

  req = request.get({url: data_url});
  req.pipe(require('JSONStream').parse([true]))
    .pipe(require('stream-batch')({maxItems: 1000}))
    .on('data', callback)
    .on('end', done);

错误:

Invalid JSON (Unexpected "I" at position 0 in state STOP)

("A" as in "Internal server error".) 似乎请求不会为完成的请求发出“错误”事件,因此添加 req.on('error', (err) => ...) 不会触发。我可以添加

req.on('response', function(res) {
  if(res.statusCode >= 400) { ... }
})

但是我似乎无法理解正文中的错误消息。

如何获取错误消息、有意义地记录并中断处理?

【问题讨论】:

    标签: node.js node-request node.js-stream


    【解决方案1】:

    由于传递给response 事件的参数也是可读流,因此您可以在其处理程序中创建管道:

    req.on('response', function(res) {
      if (res.statusCode >= 400) {
        let chunks = [];
        res.on('data', c => chunks.push(c))
           .on('end', () => {
             console.log('error', Buffer.concat(chunks).toString());
           });
      } else {
        res.pipe(require('JSONStream').parse([true]))
           .pipe(require('stream-batch')({maxItems: 1000}))
           .on('data', callback)
           .on('end', done);
      }
    })
    

    【讨论】:

    • 哦,一旦观察到,太明显了!谢谢。
    猜你喜欢
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多