Search code examples
node.jsexpressrequestjs

How to return image in NodeJS after intercepted image get request?


I am trying to intercept requests for html elements (like images and scripts) that is referenced with relative path from my website and retrieve them from a 2nd website using requestJS for NodeJS , this works with scripts but I can’t figure a way to retrieve images.
For example in my home page .html (127.0.0.1:3030) I have:

<script src="/main/mainscript.js"></script>

Intercepted to retrieve "http://my2website.com/main/mainscript.js", works fine

<img src=”/images/logo.png”/>

Intercepted to retrieve "http://my2website.com/images/logo.png", but I always get error even if I can see that the response headers attributes matches the required file.

Using this code :

app.get('*', function (req, res) {
  var options = {
    url: 'http://my2website.com'+ req.path,
    headers: {
        'User-Agent': req.headers['user-agent']
    }
  };
  request(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        res.send(body);
    }
    else {
        console.log('request error: ' + JSON.stringify(error));
        res.redirect('/');
    }
  });
});

Please forgive my poor English.


Solution

  • Set encoding: null in your options. This will keep binary data intact by keeping the response as a Buffer instance instead of converting it to a UTF-8 string:

      var options = {
        url: 'http://my2website.com'+ req.path,
        headers: {
            'User-Agent': req.headers['user-agent']
        },
        encoding: null
      };