Sven-Michael Stübe
Sven-Michael Stübe

Reputation: 14750

How to use express as pass through proxy?

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

Requirements:

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:

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

Upvotes: 5

Views: 2977

Answers (1)

Adrian Lynch
Adrian Lynch

Reputation: 8494

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

Upvotes: 1

Related Questions