我有一个外部网络服务,它返回图像。
我有调用该外部 Web 服务的 Node 快速路由。
我正在努力将外部 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 图片。
关于javascript - 从外部网络服务获取图像并将其传递给另一个快速 js 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26833191/