从外部web服务获取图像并将其传递到另一个express js路由

Get image from external web service and pass it to another express js route

本文关键字:另一个 express 路由 js 服务 web 获取 图像 从外部      更新时间:2023-09-26

我有一个外部web服务,它返回图像。

我有节点快速路由,它调用外部web服务。

我正在努力将外部web服务的返回对象(即图像)作为快递路线的返回对象

这是一个例子,我试图从外部URL获取图像,并按原样传递它。它不起作用,有人能帮我知道吗?

exports.getImage = function (req, res) {
    var http = require('http');

    var options = {
        host: 'http://www.gettyimages.co.uk',
        path: '/CMS/StaticContent/1391099215267_hero2.jpg',
        method: 'GET',
        headers: {
            "content-type": "image/jpeg"
        }
    };
    var request = http.request(options, function(response) {
        var imagedata = '';
        response.setEncoding('binary');
        response.on('data', function(chunk){
            imagedata += chunk
        });
        response.on('end', function() {
            console.log('imagedata: ', imagedata);
            res.writeHead(200, {'Content-Type': 'image/jpeg' });
            res.send(imagedata);
        });
    }).on("error", function(e) {
        console.log("Got error: " + e.message, e);
    });
    request.end();
};

现有代码的问题是,当您向res.send()传递字符串时,它默认为非二进制编码,因此您的数据最终会因此而损坏。

其次,最好只是流式传输数据,这样就不会每次都在内存中缓冲整个图像。示例:

var request = http.get(options, function(response) {
  res.writeHead(response.statusCode, {
    'Content-Type': response.headers['content-type']
  });
  response.pipe(res);
}).on("error", function(e) {
  console.log("Got error: " + e.message, e);
});

最后,host的值是错误的,它应该只是主机名(没有方案):www.gettyimages.co.uk。此外,在请求headers中设置"content-type": "image/jpeg"没有意义(可以删除),因为您在请求中没有发送jpeg图像。