pipe道图像与在请求中发送node.js中的callback主体

我正在使用node.js 0.10.33和请求2.51.0。

在下面的例子中,我构build了一个简单的Web服务器,它使用请求代理图像。 有两条路线设置代理相同的图像..

/ pipe只需将原始请求传递给响应

/ callback等待请求callback,并将响应头和主体发送给响应。

pipe道示例按预期方式工作,但callback路由不会呈现图像。 标题和主体看起来是一样的。

callback路线如何导致图像中断?

以下是示例代码:

var http = require('http'); var request = require('request'); var imgUrl = 'https://developer.salesforce.com/forums/profilephoto/729F00000005O41/T'; var server = http.createServer(function(req, res) { if(req.url === '/pipe') { // normal pipe works request.get(imgUrl).pipe(res); } else if(req.url === '/callback') { // callback example doesn't request.get(imgUrl, function(err, resp, body) { if(err) { throw(err); } else { res.writeHead(200, resp.headers); res.end(body); } }); } else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<html><head></head><body>'); // test the piped image res.write('<div><h2>Piped</h2><img src="/pipe" /></div>'); // test the image from the callback res.write('<div><h2>Callback</h2><img src="/callback" /></div>'); res.write('</body></html>'); res.end(); } }); server.listen(3000); 

结果在这

测试结果

问题是, body默认是一个(UTF-8)string。 如果你期待二进制数据,你应该在request()选项中明确地设置encoding: null 。 这样做将使body成为一个缓冲区,二进制数据保持不变:

 request.get(imgUrl, { encoding: null }, function(err, resp, body) { if(err) { throw(err); } else { res.writeHead(200, resp.headers); res.end(body); } });