Search code examples
node.jshttprequesthttp-proxy

Node.JS http get request returns undefined


This was supposed to be pretty simple but instead of getting the data back I am getting undefined.

I am behind a proxy server and I am not good at making requests from behind a proxy server. I found just one tutorial which explained http requests when using a proxy server without using an external module and that didn't explain properly.

const http = require('http');
let options = {
    host: '10.7.0.1',
    port:8080,
    path:'www.google.co.uk'
}

http.get(options,(res) => {
    let str = '';
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
    str += chunk;
})

res.on('end', (str) => {
    console.log(str);
    })
})

10.7.0.1 is the address of the proxy server and 8080 is the port.

The output of this code is undefined.

I don't even know if the method is correct and I am not able to figure it out.I read the node http docs and wrote the options object to the best of my understanding , correct me if I am wrong.

And in general how do i make requests when behind a proxy server.


Solution

  • The request package allows to make an http request in a pretty elegant way, and for specifying proxy, just need to set the value for proxy key inside the options object request takes as an argument.

    const request = require('request');
    
    request({url: 'http://example.com', proxy: 'https://host:port'}, (error, response, body) => {
      //Do whatever you want
    });