Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override node.js http to use a proxy for all outbound requests

Tags:

node.js

proxy

I recently created a node.js app that reaches out to social media sites and caches our public feeds. I'm using some existing npm modules to facilitate accessing the social media api's. It works like a charm in my dev environment but on our production environment requests are timing out because they need to go through a proxy.

Without having to modify the npm modules how can I make the outbound requests go through a proxy?

like image 784
atorres757 Avatar asked May 08 '13 14:05

atorres757


People also ask

Does NodeJS support proxy?

In the standard method, the client sends a request directly to the API endpoint to fetch the desired data. In this case, the node. js proxy will act as an intermediary between the user and the API. Thus, the user makes a request to the proxy, which is then forwarded to the API endpoint.

What is node http-proxy?

node-http-proxy is an HTTP programmable proxying library that supports websockets. It is suitable for implementing components such as reverse proxies and load balancers.

Does node js server block HTTP requests?

Your code is non-blocking because it uses non-blocking I/O with the request() function. This means that node. js is free to service other requests while your series of http requests is being fetched.


2 Answers

Use the http.globalAgent property. This will let you intercept all requests running in your process. You can then modify those requests to be properly formatted for the proxy server.

http://nodejs.org/api/http.html#http_http_globalagent

Another option is to create a proxy exception for that application.

like image 140
Jason Young Avatar answered Oct 08 '22 22:10

Jason Young


There is an npm module for that:

https://www.npmjs.com/package/global-tunnel

var globalTunnel = require('global-tunnel');

globalTunnel.initialize({
  host: '10.0.0.10',
  port: 8080,
  sockets: 50 // optional pool size for each http and https 
});

Or if you only want to proxy certain requests, you can use the tunnel package (which is the driving force behind the global tunnel above):

https://www.npmjs.com/package/tunnel

var tunnel = require('tunnel');

// create the agent
var tunnelingAgent = tunnel.httpsOverHttps({
  proxy: {
    host: 'localhost',
    port: 3128
  }
});

var req = https.request({
  host: 'example.com',
  port: 443,
  // pass the agent in your request options
  agent: tunnelingAgent
});
like image 45
Ryan Wheale Avatar answered Oct 08 '22 23:10

Ryan Wheale