Reputation: 625
I am trying to create a proxy for images based upon an input url. My current code has it copying the exact some headers and returning them to the client, but I have tried various ways and the response either keeps trying to load forever or it says "The image cannot be displayed because it contains errors". Here is my proxy:
var http = require('http'),
url = require('url');
exports.show = function (req, res, next) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var options = {
host: "api.com",
path: "/dgtf/20080303201247771409000000.jpg"
};
var callback = function(response) {
var completeResponse = '';
response.on('data', function (chunk) {
completeResponse += chunk;
});
response.on('end', function() {
res.writeHead(200, {'Content-Type': response.headers['content-type'], 'Content-Length': response.headers['content-length'] });
res.end(completeResponse, 'binary');
});
};
http.request(options, callback).end();
};
Upvotes: 3
Views: 4542
Reputation: 106736
Avoid converting binary data to strings unless you know what you are doing. You might instead try something like:
var http = require('http'),
url = require('url');
exports.show = function (req, res, next) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var options = {
host: "api.com",
path: "/dgtf/20080303201247771409000000.jpg"
};
var callback = function(response) {
if (response.statusCode === 200) {
res.writeHead(200, {
'Content-Type': response.headers['content-type']
});
response.pipe(res);
} else {
res.writeHead(response.statusCode);
res.end();
}
};
http.request(options, callback).end();
};
Upvotes: 5