koss
koss

Reputation: 874

Node.js proxy to return exact response from the external website

I'm trying to create the express.js proxy to an external website to obtaining audio data from there. I know about modules like http-proxy, but think they are excessive for the case when only one url-bound request goes through proxy. I'm using the code below:

express.get('/proxy', function (req, res) {

    var options ={
        host: "website.com",
        port: 80,
        path: "/audio/test.mp3",
        method: 'GET'
    };

    http.get(options, function (audioRes) {
        var data = [], dataLen = 0;

        audioRes.on('data', function(chunk) {
            data.push(chunk);
            dataLen += chunk.length;
        })
        .on('end', function() {
            var buf = new Buffer(dataLen);
            res.set(audioRes.headers);
            res.send(buf);
        });
    })
    .on('error', function (error) {
        console.log(error.message);
    });

});

I get response, but it cannot be decoded as a valid audio. While debugging with the Fiddler, I found out that the number of bites sent by a server mismatches the number specified in the Content-Length header (which indicates fewer bytes being retrieved).

I cannot figure out how to properly return the exact response that's been retrieved from the remote server. Would be grateful for any help.

Upvotes: 2

Views: 2139

Answers (1)

user568109
user568109

Reputation: 48003

To send request via proxy, you can set the proxy url in Host header. Also you have to specify the full URL of the external resource you are trying to access via proxy.

var http = require("http");

var options = {
  host: "proxy",
  port: 8080,
  path: "http://www.google.com",  //full URL
  headers: {
    Host: "10.1.2.3"              //your proxy location
  }
};
http.get(options, function(res) {
  console.log(res);
});

I am not sure why it is not returning full response. Can you post your options.

Update

Try this inside /proxy after putting the options

http.get(options, function (audioRes) {
    audioRes.pipe(res);
})
.on('error', function (error) {
    console.log(error.message);
});

Upvotes: 1

Related Questions