2

実験目的で単純な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よりもはるかに困難です。どんな助けでも大歓迎です。

4

1 に答える 1

3

コメントで述べたように、あなたの主な問題は、あなた.write.end呼び出しがコンテキストに適切にバインドされていないことです。そのため、それらはただひっくり返ってエラーを投げかけます。

これを修正すると、プロパティが元のリクエストのヘッダーをheadersプルするため、リクエストは404を返します。あなたの例に従うと、それはjquery.comのサーバーに送信され、404になります。プロキシする前にヘッダーを削除する必要があります。hostlocalhost:8484host

を呼び出す前にこれを追加しprotocol.requestます。

delete options.headers.host;
于 2012-04-19T07:08:09.503 に答える