I'm trying to create a simple node.js proxy server for experimental purposes and I came up with this simple script:
var url = require("url");
var http = require("http");
var https = require("https");
http.createServer(function (request, response) {
var path = url.parse(request.url).path;
if (!path.indexOf("/resource/")) {
var protocol;
path = path.slice(10);
var location = url.parse(path);
switch (location.protocol) {
case "http:":
protocol = http;
break;
case "https:":
protocol = https;
break;
default:
response.writeHead(400);
response.end();
return;
}
var options = {
host: location.host,
hostname: location.hostname,
port: +location.port,
method: request.method,
path: location.path,
headers: request.headers,
auth: location.auth
};
var clientRequest = protocol.request(options, function (clientResponse) {
response.writeHead(clientResponse.statusCode, clientResponse.headers);
clientResponse.on("data", response.write);
clientResponse.on("end", function () {
response.addTrailers(clientResponse.trailers);
response.end();
});
});
request.on("data", clientRequest.write);
request.on("end", clientRequest.end);
} else {
response.writeHead(404);
response.end();
}
}).listen(8484);
I don't know where I'm going wrong but it gives me the following error when I try to load any page:
http.js:645
this._implicitHeader();
^
TypeError: Object #<IncomingMessage> has no method '_implicitHeader'
at IncomingMessage.<anonymous> (http.js:645:10)
at IncomingMessage.emit (events.js:64:17)
at HTTPParser.onMessageComplete (http.js:137:23)
at Socket.ondata (http.js:1410:22)
at TCP.onread (net.js:374:27)
I wonder what could the problem be. Debugging in node.js is so much more difficult than in Rhino. Any help will be greatly appreciated.
As I mentioned in the comments, your primary problem is that your .write
and .end
calls are not bound properly to a context, so they will just flip out and throw errors all over.
With that fixed, requests give a 404 because the headers
property will pull in the host
header of the original request, localhost:8484
. Following your example, that will get send to jquery.com's server, and it will 404. You need to remove the host
header before proxying.
Add this before calling protocol.request
.
delete options.headers.host;