Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS image proxy

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();
};
like image 546
user1200387 Avatar asked Jul 30 '26 12:07

user1200387


1 Answers

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();
};
like image 170
mscdex Avatar answered Aug 01 '26 02:08

mscdex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!