Node JS: Making https request via proxy

Struggled quite a bit before getting this worked. Had a requirement where I had to make a GET/POST call from node JS code to external webservice API over tunnel proxy. Posting multiple solutions that worked for me:

Using https-proxy-agent module and request module

Install the following modules:

npm install -g request https-proxy-agent

In case you are connecting to an http:// endpoint, you could install:

npm install -g http-proxy-agent

Then:

var HttpsProxyAgent = require('https-proxy-agent');
var request = require('request');
var proxy = 'http://127.0.0.1:3128';
var agent = new HttpsProxyAgent(proxy);
request({
	uri: "https://example.com/api",
	method: "POST",
	headers: {
		'content-type': 'application/x-www-form-urlencoded'
	},
	agent: agent,
	timeout: 10000,
	followRedirect: true,
	maxRedirects: 10,
	body: "name=john"
}, function(error, response, body) {
	console.log("Error" + error);
	console.log("Response: " + response);
	console.log("Body: " + body);
});

Using https-proxy-agent module and https module

var https = require('https');
var HttpsProxyAgent = require('https-proxy-agent');
var proxy = 'http://127.0.0.1:3128';
var agent = new HttpsProxyAgent(proxy);
var post_req = https.request({
	host: 'example.com',
	port: '443',
	path: '/api',
	method: 'POST',
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded'
	},
	agent: agent,
	timeout: 10000,
	followRedirect: true,
	maxRedirects: 10
}, function(res) {
	res.setEncoding('utf8');
	res.on('data', function(chunk) {
		console.log('Response: ' + chunk);
	});
});
post_req.write("name=john");
post_req.end();

References:

https://nodejs.org/api/https.html

http://blog.vanamco.com/proxy-requests-in-node-js/ (Custom implementation of HttpsProxyAgent)

https://www.npmjs.com/package/https-proxy-agent

0 Comments 0 Comments
0 Comments 0 Comments