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

标签 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 中困难得多。任何帮助将不胜感激。

最佳答案

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

修复此问题后,请求会给出 404,因为 headers 属性将引入原始请求的 host header ,localhost:8484 。按照您的示例,它将发送到 jquery.com 的服务器,并且会出现 404。您需要在代理之前删除 host header 。

在调用protocol.request之前添加此内容。

delete options.headers.host;

关于javascript - 使用node.js实现简单的代理服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10222216/

相关文章:

javascript - 将 Xcode 与 Javascript/Coffeescript 和 Titanium 一起使用?

javascript - Express 和 AngularJS 路由

javascript - 使用 Javascript 手动插入 ObjectId

php - PHP邮件的替代品

javascript - 在 Meteor.js 上返回多个游标

node.js - Nodejs 在 req.session.data 中设置对象但在下一个请求中没有获取该数据?

javascript - 自定义拼写检查器 Javascript

c - 套接字 http 请求失败

http - Nginx 将 Http 重定向到 Https - 这里有什么问题?

node.js - 只获取每个用户的一份文档 - mongoDB