如何修改管道以返回自定义响应? [英] How to modify pipe to return custom response?

查看:80
本文介绍了如何修改管道以返回自定义响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I return a custom response (or error) to the client side with request library? The .pipe() will always pipe the original response back to the client

这将返回原始响应

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);

这将返回我的自定义响应

This returns my custom response

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);

是否可以根据响应控制是否通过管道传输?

Is it possible to control whether not to pipe it based on the response?

推荐答案

该请求将在收到响应后立即开始管道传输.如果您想根据收到的状态代码控制管道,或者不控制管道,则必须在响应回调上进行管道调用,如下所示:

The request will start piping as soon as it receives a response. If you want to control piping or not based on the status code you receive, you'll have to make the pipe call on the response callback like this:

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');
    }
  });

这篇关于如何修改管道以返回自定义响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆