将响应流化为HTTP响应 [英] Stream Response into HTTP Response

查看:59
本文介绍了将响应流化为HTTP响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API试图向向该API发送HTTP请求并将其返回给我的API发出HTTP请求,然后将该图像重新发送给向我发出请求的客户端,或者等待直到该图像被发送至我,并立即将其全部发送.

I have an API that is trying to make an HTTP request to an API that streams and image back to the me, then either stream that image back to the client making the request to me or wait until the image has been streamed to me and send it all at once.

我正在使用Express和请求承诺.

I am using Express and request-promise.

这是我的代码的简化版本.

Here's a shortened version of my code.

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;

我返回的图像只是我假设的二进制数据,我不知道是否需要在请求承诺级别执行某些操作以实现此权利,或者何时将其发送回客户端.

The image that I get back is just what I assume is the binary data and I don't know if I need to do something at the request-promise level to make that right or when I send it back to the client.

我在localhost:8080上运行的服务器模仿了当一切都说完之后我将要命中的实际服务器.

The server that I have running at localhost:8080 mimics the actual server that I will be hitting when this is all said and done.

推荐答案

您可以直接通过管道传输流,而不必使用request-promise.

You could pipe the streams directly rather than using 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;

这篇关于将响应流化为HTTP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆