send request via a proxy in javascript

To send a request via a proxy in JavaScript, we can make use of the http module in Node.js along with the request package.

Here's an example code snippet that demonstrates how to send a GET request via a proxy:

const request = require('request');

const options = {
  url: 'http://example.com',
  proxy: 'http://user:pass@proxyserver:port'
};

request.get(options, (error, response, body) => {
  if (error) {
    console.error(error);
  } else {
    console.log(body);
  }
});
266 chars
15 lines

In the above code, we first import the request package and then define an options object with the URL we want to send a request to and the proxy server details. The proxy property of the options object should contain the proxy URL in the format http://username:password@proxyserver:port.

Finally, we call the request.get method with the options object as the first parameter and a callback function as the second parameter. The callback function receives three parameters: error, response, and body. If there is an error, we log it to the console, else we log the response body.

Note that if you don't require a proxy that needs authentication, you can omit the username and password parts of the proxy URL.

gistlibby LogSnag