How to use an http proxy with Node.js http.Client?

Sometimes, we want to use an http proxy with Node.js http.Client.

In this article, we’ll look at how to use an http proxy with Node.js http.Client.

How to use an http proxy with Node.js http.Client?

To use an http proxy with Node.js http.Client, we can use the http.get method to connect to the proxy.

For instance, we write

const http = require("http");

const options = {
  host: "proxy",
  port: 8080,
  path: "http://www.google.com",
  headers: {
    Host: "www.google.com"
  }
};

http.get(options, (res) => {
  console.log(res);
  res.pipe(process.stdout);
});

to call http.get with the options for the connection.

We set the host to the proxy URL.

path has the path that we want to proxy with the proxy.

And headers has the Host with the host URL to proxy.

In the get callback, we get the response from res.

Conclusion

To use an http proxy with Node.js http.Client, we can use the http.get method to connect to the proxy.