Skip to content

Instantly share code, notes, and snippets.

@fracasula
Last active November 28, 2019 16:12
Show Gist options
  • Save fracasula/d15ae925835c636a5672311ef584b999 to your computer and use it in GitHub Desktop.
Save fracasula/d15ae925835c636a5672311ef584b999 to your computer and use it in GitHub Desktop.
Node.js basic example for proxy to http server
/**
* Once this is running open your browser and hit http://localhost
* You'll see that the request hits the proxy and you get the HTML back
*/
'use strict';
const net = require('net');
const http = require('http');
const PROXY_PORT = 80;
const HTTP_SERVER_PORT = 8080;
let proxy = net.createServer(socket => {
socket.on('data', message => {
console.log('---PROXY- got message', message.toString());
let serviceSocket = new net.Socket();
serviceSocket.connect(HTTP_SERVER_PORT, 'localhost', () => {
console.log('---PROXY- Sending message to server');
serviceSocket.write(message);
});
serviceSocket.on('data', data => {
console.log('---PROXY- Receiving message from server', data.toString();
socket.write(data);
});
});
});
let httpServer = http.createServer((req, res) => {
switch (req.url) {
case '/':
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<html><body><p>Ciao!</p></body></html>');
break;
default:
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('404 Not Found');
}
});
proxy.listen(PROXY_PORT);
httpServer.listen(HTTP_SERVER_PORT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment