Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve image in node.js fetched from another server

I feel like this should be simple enough, but I am having trouble making this work. I have a URL that the front-end hits. This triggers node to fetch an image from another server. Next I want node to send the image as the response. This part is not working for me.

render: function(img,response){
    request.get(URL, function (error, res, body) {
        if (!error && res.statusCode == 200) {
            response.setHeader('Content-Type', 'image/png');
            response.writeHead(200);
            response.write(body);
            response.end();
        }
    });
}

Should I be buffering the image instead?

FYI I am trying to do this this way because the image i need to retrieve as authentication credentials in the src path, and I don't want those exposed to the user. So if you think that there is a better solution than what I am trying, please feel free to suggest. :)

Thanks!

like image 777
Trey Eckels Avatar asked May 07 '26 18:05

Trey Eckels


1 Answers

If someone is looking for an answer and the above did not work for you, try the request module like this.

First include the module

var request = require('request')

then:

request.get(URL, {encoding:'binary'},function(error, response){
             res.writeHead(200, {'Content-Type': 'image/jpeg', 'Cache-Control': 'no-cache' });
             res.end(response.body, 'binary');
        });

This will bypass the image from the URL and print it into the response.

like image 169
Rod Navarro Avatar answered May 09 '26 15:05

Rod Navarro



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!