使用node.js实现简单的代理服务器

时间:2012-04-19 05:35:23

标签: javascript http node.js https proxy-server

我正在尝试创建一个简单的node.js代理服务器用于实验目的,我想出了这个简单的脚本:

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);

我不知道我哪里出错了但是当我尝试加载任何页面时它会给我以下错误:

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)

我想知道问题是什么。 node.js中的调试比Rhino困难得多。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

正如我在评论中提到的,您的主要问题是您的.write.end调用未正确绑定到上下文,因此它们只会翻转并全部抛出错误。

修复后,请求会提供404,因为headers属性会引入原始请求的host标头localhost:8484。按照您的示例,将发送到jquery.com的服务器,它将是404.您需要在代理之前删除host标头。

在致电protocol.request之前添加此内容。

delete options.headers.host;