Skip to content

Instantly share code, notes, and snippets.

@bhongy
Created August 7, 2018 17:33
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment