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:
get
for all requests (HEAD, GET, ...)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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With