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

时间:2015-11-30 09:10:03

标签: node.js api rest http http-streaming

所以,我正在使用节点创建REST API,我必须创建一个路由。 路线的目的:充当代理服务器并拨打不同的外部网站,并将其获得的响应返回到原始请求。 到目前为止,我有以下代码,它可以工作:

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响应。通过这种方式,我的意思是我希望将响应作为流进行处理,并在它进入块时立即返回。 这可能吗?

2 个答案:

答案 0 :(得分:2)

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

<ul class="nav" id="usrList">
    <li ng-repeat="user in users" ng-init="sectionIndex = $index" id={{user.uid}} name={{$index}} 
        ng-click="fillUserForm($event)">{{user.mobile + " / " + user.email}} 
      <input type="checkbox" style="float:right;" ng-model="usersCheck[$index]" 
           ng-change="activeInactiveUser(sectionIndex.uid,usersCheck[$index])" 
           ng-checked="usersCheck[$index]" />
    </li>
</ul>

答案 1 :(得分:1)

通过请求,您可以直接将传入响应管道传输到文件流,其他请求或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);
    }
)