Skip to content

Instantly share code, notes, and snippets.

@andreldm
Created March 19, 2020 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreldm/ad3f9f1790ff2c8d51b63fd82ca8d9c9 to your computer and use it in GitHub Desktop.
Save andreldm/ad3f9f1790ff2c8d51b63fd82ca8d9c9 to your computer and use it in GitHub Desktop.
Express Proxy POC
const express = require('express');
const proxy = require('express-http-proxy');
const app = express();
app.use(express.static('static'));
app.use('/proxy', proxy((req) => req.header('X-Proxy-Target')));
app.listen(3000, () => console.log("App running at port 3000"));
<!DOCTYPE html>
<html lang="en">
<!-- place in a 'static' folder -->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Express Proxy POC</title>
<style>
body>* {
margin-top: 16px;
}
</style>
</head>
<body>
<div>
<label for="es">Elasticsearch URL</label>
<input id="es" value="http://localhost:9200">
</div>
<div>
<label for="query">Query</label>
<input id="query" value="_cat/indices">
</div>
<div>
<label for="method">Method</label>
<input id="method" value="GET">
</div>
<div>
<div>
<label for="body">Body</label>
</div>
<textarea id="body" rows="10" cols="60"></textarea>
</div>
<div>
<button onclick="test(false)">Test direct connection</button>
<button onclick="test(true)">Test proxied connection</button>
</div>
<textarea id="result" rows="20" cols="80" readonly></textarea>
<script>
function getBody() { return getMethod() == 'GET' ? undefined : document.getElementById('body').value; }
function getPath() { return `${document.getElementById('query').value}?format=json&pretty`; }
function getMethod() { return document.getElementById('method').value; }
function getURL() { return `${document.getElementById('es').value}/${getPath()}` }
function test(proxy) {
var url = getURL();
var options = {
body: getBody(),
method: getMethod(),
headers: { 'Content-Type': 'application/json' }
}
if (proxy) {
url = 'http://localhost:3000/proxy/' + getPath();
options.headers['X-Proxy-Target'] = getURL();
}
fetch(url, options)
.then((response) => { return response.text(); })
.then((data) => { document.getElementById('result').innerHTML = data; })
.catch((error) => { document.getElementById('result').innerHTML = error; });
}
</script>
</body>
</html>
{
"name": "express-proxy-poc",
"version": "0.0.1",
"main": "app.js",
"dependencies": {
"express": "^4.17.1",
"express-http-proxy": "^1.6.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment