web-dev-qa-db-ja.com

HTTPレスポンスへのレスポンスのストリーミング

私にストリーミングして画像を返すAPIにHTTPリクエストを送信しようとしているAPIがあります。その画像をストリーミングしてクライアントにリクエストを送信するか、画像がストリーミングされて送信されるまで待機します。それをすべて一度に。

Expressとrequest-promiseを使用しています。

これが私のコードの短縮版です。

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で実行しているサーバーは、これがすべて実行されたときにヒットする実際のサーバーを模倣しています。

5
loganhuskins

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;
13
skirtle