【问题标题】:How to modify pipe to return custom response?如何修改管道以返回自定义响应?
【发布时间】:2018-07-18 02:28:03
【问题描述】:

如何使用request 库向客户端返回自定义响应(或错误)? .pipe() 将始终通过管道将原始响应返回给客户端

这会返回原始响应

request(options)
    .on('error', err => {
      return cb(err);
    })
    .on('response', response => {
      // This is an error
      if (response.statusCode === 500) {
        const error = new Error('File not found');
        return cb(error);
      }
      return cb(null, response, 'application/pdf');
    })
    .pipe(res);

这将返回我的自定义响应

request(options)
    .on('error', err => {
      return cb(err);
    })
    .on('response', response => {
      // This is an error
      if (response.statusCode === 500) {
        const error = new Error('File not found');
        return cb(error);
      }
      return cb(null, response, 'application/pdf');
    });
    // .pipe(res);

是否可以根据响应控制是否不进行管道传输?

【问题讨论】:

    标签: node.js request pipe


    【解决方案1】:

    一旦您从流中读取,该数据将不会通过管道传输到其他地方,因此您无法读取内容的第一部分,然后决定您要传输整个内容,然后调用 .pipe()并期望您已经阅读的原始内容包含在管道响应中。

    您也许可以阅读一些内容,准确记录您阅读的内容,然后如果您决定只是想通过管道传输它,您可以发送您已经阅读的内容并致电.pipe()。您必须自己进行测试,看看是否有任何竞争条件可能导致您丢失一些数据。

    如果数据不是很大,一个相对简单的事情是读取所有数据(request() 库可以用于为您获取所有响应的模式),然后一旦你有所有数据,您可以检查数据并决定发送什么。您可以发送原始数据,也可以对其进行修改并发送修改后的数据,或者您可以决定发送不同的数据。

    【讨论】:

    • 完全有道理!我尝试使用async/await 来收集响应,但它不起作用.. 你能帮忙举一个简单的例子吗?
    • @JeeMok - 和往常一样,很难帮助我们看不到的代码,所以有机会帮助你编写代码,你必须将它添加到你的问题中我们可以看到你想做什么。
    【解决方案2】:

    请求将在收到响应后立即开始管道传输。如果您想根据收到的状态代码控制管道或不控制管道,则必须像这样对响应回调进行管道调用:

    const req = request(options)
      .on('error', err => cb(err))
      .on('response', response => {
        // This is an error
        if (response.statusCode === 500) {
          const error = new Error('File not found');
          return cb(error);
        }
    
        if (typeof response.end === 'function') {
          req.pipe(response);
        }
        if (response.req.finished) {
          return cb(null, response, 'application/pdf');
        }
      });
    

    【讨论】:

    • 它给了我一个Error 500 You cannot pipe after data has been emitted from the response. Error: You cannot pipe after data has been emitted from the response.
    • 我刚刚修复了代码,它是res(外部响应对象)而不是response
    • 这会将您对res 流的请求的响应进行管道传输。请注意,如果您的 cb 回调也将数据发送到 res 流,您可能会收到相同的错误。
    • 对不起,当我做req.pipe(res)时发生错误。它适用于req.pipe(response),除了我们在回调之前在错误处理程序中放置了req.end();。感谢您的帮助!!!
    • 我已经更新了您对工作代码的回答。请查看它,我会将其设置为答案。再次感谢@Augusto!
    猜你喜欢
    • 2019-10-28
    • 1970-01-01
    • 2019-11-10
    • 2021-01-08
    • 2017-03-26
    • 2021-04-09
    • 2021-05-10
    • 2021-07-13
    • 2020-04-23
    相关资源
    最近更新 更多