Last active
November 28, 2019 16:12
-
-
Save fracasula/d15ae925835c636a5672311ef584b999 to your computer and use it in GitHub Desktop.
Node.js basic example for proxy to http server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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