How to use express as a pass through a proxy?

How to create an express server that acts as a proxy?

Requirements:

  • http + https
  • works for a corporate proxy.
  • option to return custom content for some URLs

I have 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 help request. But there are some problems.

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...');
});

Problems with this approach:

  • it uses getfor all requests (HEAD, GET, ...)
  • source request headers are not passed
  • https does not work.

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 (possibly due to a 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 .npmrcalso contains proxies.

proxy=http://mycorporateproxy.com:8080
https-proxy=http://mycorporateproxy.com:8080
+4
1

http-proxy-middleware :

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}`))

https, : https://github.com/chimurai/http-proxy-middleware#http-proxy-options

0

Source: https://habr.com/ru/post/1668256/


All Articles