Skip to content

Instantly share code, notes, and snippets.

@tmsnvd
Created November 28, 2018 22:54
Show Gist options
  • Save tmsnvd/713d5f13ff5ed703dc7dd4570196670d to your computer and use it in GitHub Desktop.
Save tmsnvd/713d5f13ff5ed703dc7dd4570196670d to your computer and use it in GitHub Desktop.
const http = require('http');
const httpProxy = require('http-proxy');
const express = require('express'),
bodyParser = require('body-parser');
// listen port
const port = 9997;
// create proxy server
const proxy = httpProxy.createProxyServer({});
proxy.on('proxyReq', function (proxyReq, req, res, options) {
if (req.body) {
let bodyData = JSON.stringify(req.body);
console.log(bodyData);
proxyReq.setHeader('Content-Type', 'application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
// Stream the content
proxyReq.write(bodyData);
}
});
proxy.on('proxyRes', function (proxyRes, req, res) {
var body = new Buffer('');
proxyRes.on('data', function (data) {
body = Buffer.concat([body, data]);
});
proxyRes.on('end', function () {
body = body.toString();
console.log(body);
res.end("my response to cli");
});
});
const app = express()
.use(bodyParser.json()) //json parser
//.use(bodyParser.urlencoded()) //urlencoded parser
.use(function (req, res) {
const fqdn = req.headers.host.split(':')[0];
const hostname = fqdn.split('.')[0];
const target = 'http://localhost:8080';
// proxy the request upstream
proxy.web(req, res, {
target: target
});
console.log(`Routing ${req.headers.host} to ${target}`);
});
http.createServer(app).listen(port, function(){
console.log('proxy on 8013');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment