Search code examples
javascriptnode.jshttp-proxy

Node http-proxy not working behind proxy


I am using the http-proxy-middleware module, which is an express middleware. the middleware module relies on http-proxy. The node host is running behind a proxy. I want to forward certain routes to a different service (for test purposes let's assume httpbin.org). So I defined the proxy as follows.

var proxy = require('http-proxy-middleware');
var aeProxy = proxy({
    target: 'http://httpbin.org',
    changeOrigin: true,
    pathRewrite: {
        '^/api/ae':'/get'
    }
});
app.use('/api/ae', proxy);

I have also set the respective env variables (from debugging console):

process.env.HTTP_PROXY
> "http://proxy:8080"
process.env.HTTPS_PROXY
> "http://proxy:8080"

Unfortunately I only get timeouts. When running the node script in an environment without a proxy it works as expected.

Is my configuration wrong?


Solution

  • Credit to chimurai for this on how to connect via a corporate proxy via the agent field.

    var HttpsProxyAgent = require('https-proxy-agent');
    var proxy = require("http-proxy-middleware");
    
    // corporate proxy to connect to via environment variables
    var proxyServer = process.env.HTTPS_PROXY ||
                      process.env.HTTP_PROXY;
    
    var options = {
        target: 'http://localhost:3000',//Proxy url
        agent: new HttpsProxyAgent(proxyServer)//The actual corporate proxy sever 
    };
    
    var apiProxy = proxy('/api', options);