Created
August 7, 2018 17:33
-
-
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.
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
// 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
It doesn't work for 443 port because hostname does not match