Skip to content

Instantly share code, notes, and snippets.

@bhongy
Created August 7, 2018 17:33
Show Gist options
  • Save bhongy/2e6f0a9f9932ab6d1c43b013a7ad773a to your computer and use it in GitHub Desktop.
Save bhongy/2e6f0a9f9932ab6d1c43b013a7ad773a to your computer and use it in GitHub Desktop.
[nodejs] A simple example how to write a proxy server piping server request to client request / client response back to server response.
// from: http://book.mixu.net/node/ch10.html
'use strict';
const http = require('http');
const url = require('url');
const server = http.createServer((sreq, sres) => {
const { pathname } = url.parse(sreq.url);
const opts = {
host: 'example.com',
port: 80,
path: pathname,
method: sreq.method,
headers: sreq.headers,
}
const creq = http.request(opts, (cres) => {
// passthrough status code and headers
sres.writeHead(cres.statusCode, cres.headers);
cres.pipe(sres);
});
sreq.pipe(creq);
});
server.listen(8080, 'localhost', () => {
console.log('server is running');
});
@alexey-sh
Copy link

It doesn't work for 443 port because hostname does not match

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment