Skip to content

Instantly share code, notes, and snippets.

@detj
Last active November 12, 2020 13:31
Show Gist options
  • Save detj/e8217323d93ee3677fc6cb6d258f8e34 to your computer and use it in GitHub Desktop.
Save detj/e8217323d93ee3677fc6cb6d258f8e34 to your computer and use it in GitHub Desktop.
Forward proxy in Express
const http = require("http");
const express = require("express");
const app = express();
const HOST = "localhost";
const PORT = 4000;
const PROXY_PORT = 8080;
setupProxy();
function setupProxy() {
app.all("/v1*", function (req, res) {
var opts = {
host: HOST,
port: PORT,
path: req.url,
method: req.method,
headers: req.headers,
agent: false,
};
var request = http.request(opts);
request.on("response", function (response) {
// set status code
if (response.statusCode) res.status(response.statusCode);
// set headers
if (response.headers) res.set(response.headers);
response.pipe(res);
});
req.pipe(request);
});
}
app.listen(PROXY_PORT, () => {
console.log(`proxy server listening on port ${PROXY_PORT}`);
console.log(
`send request to http://${HOST}:${PROXY_PORT}/v1/* to forward it to http://${HOST}:${PORT}`
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment