2017-09-10 9 views
1

APIにHTTPリクエストを作成して私にストリームして返すAPIを持っていて、そのイメージをクライアントにストリームしてリクエストを出してから、イメージは私にストリームされ、すべてを一度に送信します。HTTPレスポンスへのストリームレスポンス

私は、Expressとリクエストを約束しています。

ここに私のコードの短縮版があります。

const express = require('express'); 
const router = express.Router(); 
const request = require('request-promise'); 

const imgFunc = async() => { 
    try { 
    const response = await request.get({ 
     method: 'GET', 
     uri: `http://localhost:8080`, 
    }); 
    return response; 
    } catch(err) { 
    console.log(err); 
    } 
}; 

router.get('/', async function(req, res, next) { 
    try { 
    const response = await imgFunc(); 
    return res.send(response); 
    } catch (err) { 
    console.log(err); 
    } 
}); 

module.exports = router; 

私は戻って取得画像は、私はバイナリデータであると仮定し、私は戻ってそれを送信するとき、私はその権利を行うことが要求約束レベルで何かをする必要があり、または場合、私は知らない何だけですクライアントに送信します。

localhost:8080で実行しているサーバーは、これがすべて実行されたときに私が打つ実際のサーバーを模倣しています。

答えて

1

request-promiseではなく、ストリームを直接パイプすることができます。

const express = require('express'); 
const router = express.Router(); 
const https = require('https'); 

router.get('/', function(req, res) { 
    const url = 'https://www.gravatar.com/avatar/2ea70f0c2a432ffbb9e5875039645b39?s=32&d=identicon&r=PG&f=1'; 

    const request = https.get(url, function(response) { 
     const contentType = response.headers['content-type']; 

     console.log(contentType); 

     res.setHeader('Content-Type', contentType); 

     response.pipe(res); 
    }); 

    request.on('error', function(e){ 
     console.error(e); 
    }); 
}); 

module.exports = router; 

それともrequest-promiseが基づいているrequestライブラリを使用して:第二の方法でも、要求の約束で素晴らしい作品

const express = require('express'); 
const router = express.Router(); 
const request = require('request'); 

router.get('/', function(req, res) { 
    const url = 'https://www.gravatar.com/avatar/2ea70f0c2a432ffbb9e5875039645b39?s=32&d=identicon&r=PG&f=1'; 

    request.get(url).pipe(res); 
}); 

module.exports = router; 
+0

。私の唯一の手は、ルータ自体に要求を出すロジックを持たなければならず、以前のようにイメージを返す別の機能ではないということです。 – loganhuskins

+0

さらに、これはresを "返す"ことはできません。これは通常は従うイディオムです。私はそれが大したことだとは思わないが、それは注目に値する。 – loganhuskins

関連する問題