Created
November 6, 2011 09:07
-
-
Save mizzy/1342667 to your computer and use it in GitHub Desktop.
Simple proxy made by node.js
This file contains hidden or 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
var http = require('http'); | |
var url = require('url'); | |
var proxy = http.createServer(function(req, res) { | |
var request = url.parse(req.url); | |
options = { | |
host: request.hostname, | |
port: request.port || 80, | |
path: request.path, | |
method: req.method, | |
headers: req.headers, | |
}; | |
var backend_req = http.request(options, function(backend_res) { | |
res.writeHead(backend_res.statusCode, backend_res.headers); | |
backend_res.on('data', function(chunk) { | |
res.write(chunk); | |
}); | |
backend_res.on('end', function() { | |
res.end(); | |
}); | |
}); | |
req.on('data', function(chunk) { | |
backend_req.write(chunk); | |
}); | |
req.on('end', function() { | |
backend_req.end(); | |
}); | |
}); | |
proxy.listen(8000); |
Thanks :D
This version proxies to a https upstream:
const http = require('http');
const https = require('https');
const url = require('url');
const proxy = https.createServer((req, res) => {
const request = url.parse(req.url);
const options = {
host: request.hostname,
port: request.port || 443,
path: request.path,
method: req.method,
headers: req.headers,
};
console.log(`${options.method} https://${options.host}${options.path}`);
const backend_req = https.request(options, (backend_res) => {
res.writeHead(backend_res.statusCode, backend_res.headers);
backend_res.on('data', (chunk) => {
res.write(chunk);
});
backend_res.on('end', () => {
res.end();
});
});
req.on('data', (chunk) => {
backend_req.write(chunk);
});
req.on('end', () => {
backend_req.end();
});
});
proxy.listen(8080);
@lucaswxp you made an error line 18 : https.request
must be http.request
. :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks :D
8 years later, little refactor