Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use express as pass through proxy?

How can I create a express server that acts as proxy?

Requirements:

  • http + https
  • works behind corporate proxy
  • option to return special content for some urls

I tried http-proxy, express-http-proxy, https-proxy-agent, request. I could not figure out how to use them correctly.

using request

The best result I got with request. But there are some issues.

var express = require('express'),
    request = require('request'),
    app = express();

var r = request.defaults({'proxy':'http://mycorporateproxy.com:8080'});
function apiProxy() {
    return function (req, res, next) {
        console.log(req.method);
        r.get(req.url).pipe(res);    
    }
}

app.use(apiProxy());

app.listen(8080, function () {
    'use strict';
    console.log('Listening...');
});

Issues with this approach:

  • it uses get for all requests (HEAD, GET, ...)
  • headers of the source request are not passed
  • https isn't working

using http-proxy

var express = require('express'),
    httpProxy = require('http-proxy'),
    app = express();

var proxy = httpProxy.createProxyServer({
});

function apiProxy() {
    return function (req, res, next) {
        console.log(req.method);
        proxy.web(req, res, {target: req.url});
    }
}

app.use(apiProxy());

app.listen(8080, function () {
    'use strict';
    console.log('Listening...');
});

here I get (probably because of the missing corporate proxy)

Error: connect ECONNREFUSED xx.xx.xx.xx:80
    at Object.exports._errnoException (util.js:1026:11)
    at exports._exceptionWithHostPort (util.js:1049:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1085:14)

I started google chrome with the option

--proxy-server="localhost:8080"

My .npmrc contains the proxies as well.

proxy=http://mycorporateproxy.com:8080
https-proxy=http://mycorporateproxy.com:8080
like image 989
Sven-Michael Stübe Avatar asked Nov 08 '22 02:11

Sven-Michael Stübe


1 Answers

I've successfully used http-proxy-middleware with the following:

const express = require("express")
const app = require("express")()
const proxy = require("http-proxy-middleware")
const package = require("./package.json")

const target = process.env.TARGET_URL
const port = process.env.PORT

const wildcardProxy = proxy({ target })

app.use(wildcardProxy)

app.listen(config.port, () => console.log(`Application ${package.name} (v${package.version}) started on ${config.port}`))

I haven't had the need for https yet but it's mentioned in the docs: https://github.com/chimurai/http-proxy-middleware#http-proxy-options

like image 87
Adrian Lynch Avatar answered Nov 14 '22 20:11

Adrian Lynch