I have a little code:
var target = 'http://i.stack.imgur.com/5CXfX.png'; //For example, a .PNG image
//Testing with text/html and text/plain and image/png
res.setHeader( 'Content-Type', 'image/png' );//res is response of current request
http.get( url.parse( target ), function( response ) {
var data;
response.on( 'data', function( chunk ) {
if( !data ) data = chunk; else data += chunk;
}).on('end', function() {
res.send( data );
});
});
Which fetches data from target, and display it to the browser, depends on the Content-Type I set. As of now, it works very well in fetching document and display it as HTML or plain text. However, when changing the target to a direct image URL, and change Content-Type to corresponding type of file (such as image/png or image/jpeg), the image is broken. Even when I tried to download the image, its size (Content-Length) is just like the original size, but no program can open it because it is broken. I'm not quite sure how it works with text and html but not with images (even though the Content-Type has been set correctly)?
You should just pipe the response instead unless you really need to buffer it for some reason. Example:
var target = 'http://i.stack.imgur.com/5CXfX.png';
http.get(target, function(response) {
if (response.statusCode === 200) {
res.setHeader('Content-Type', 'image/png');
return response.pipe(res);
}
// drain the response and discard it
response.resume();
res.send(response.statusCode);
});