[英]While creating a REST API in node, How can I stream http response from a request made to an external website to the original api call?
所以,我正在使用節點創建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響應。 通過這種方式,我的意思是我希望將響應作為流進行處理,並在它進入塊時立即返回。 這可能嗎?
您可以將來自外部源的傳入響應直接傳遞到應用程序發送到瀏覽器的響應,如下所示:
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);
}
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.