Node.js 在节点中创建RESTAPI时,如何将对外部网站的请求的http响应流式传输到原始API调用?

Node.js 在节点中创建RESTAPI时,如何将对外部网站的请求的http响应流式传输到原始API调用?,node.js,api,rest,http,http-streaming,Node.js,Api,Rest,Http,Http Streaming,所以,我正在使用node创建一个restapi,我必须创建一个路由。 路由的目的:充当代理服务器,调用不同的外部网站,并返回它对原始请求的响应。 到目前为止,我有以下代码,它可以工作: app.post('/v1/something/:_id/proxy', function(req, res, next) { // Basically make a request call to some external website and return // t

所以,我正在使用node创建一个restapi,我必须创建一个路由。 路由的目的:充当代理服务器,调用不同的外部网站,并返回它对原始请求的响应。 到目前为止,我有以下代码,它可以工作:

app.post('/v1/something/:_id/proxy',
    function(req, res, next) {
        // Basically make a request call to some external website and return
        // the response I get from that as my own response
        var opts = {/*json containing proper uri, mehtod and json*/}
        request(opts, function (error, responseNS, b) {
            if(error) return callback(error)
            if(!responseNS) return callback(new Error('!response'))

            return res.json(responseNS.body)
        })
    }
)
我的问题是,如何流式传输从外部网站获得的http响应。我的意思是,我希望以流的形式获得响应,并在它以块的形式出现时继续返回它。
这可能吗

您可以通过管道将来自外部源的传入响应直接传输到应用程序发送到浏览器的响应,如下所示:

app.post('/v1/something/:_id/proxy',
function(req, res, next) {
    // Basically make a request call to some external website and return
    // the response I get from that as my own response
    var opts = {/*json containing proper uri, mehtod and json*/}
    request(opts, function (error, responseNS, b) {
        if(error) return callback(error)
        if(!responseNS) return callback(new Error('!response'))

        return res.json(responseNS.body)
    }).pipe(res);
});

通过请求,您可以直接将传入的响应传递到文件流、其他请求或api发送到浏览器的响应。像

function (req, res, next) {
    request
      .get('http://example.com/doodle.png')
      .pipe(res)    
}
同样,在你的情况下,只是管道的反应

app.post('/v1/something/:_id/proxy',
    function(req, res, next) {
        // Basically make a request call to some external website and return
        // the response I get from that as my own response
        var opts = {/*json containing proper uri, mehtod and json*/}
        request(opts, function (error, responseNS, b) {
            if(error) return callback(error)
            if(!responseNS) return callback(new Error('!response'))
        }).pipe(res);
    }
)

你的意思是,一旦从外部网站的请求接收到一个区块,你就想返回它吗?如果你想通过管道传递它,你不应该在选项中使用json标志,因为在这种情况下你不应该关心内容。该标志隐式激活JSON反序列化,这将需要一个完整的响应缓冲区才能反序列化。@LazarevAlexandr:是的。只有一个问题,“管道”是否解决了在我们收到响应块后立即发送响应块的目的?