node.js - 通过将 http 服务器传送到 http 请求的简单 node.js 代理

标签 node.js http proxy

尝试通过制作一个简单的 http 代理服务器来了解有关 node.js 的更多信息。使用场景很简单:用户->代理->服务器->代理->用户

以下代码一直有效,直到最后一步。找不到将连接器的输出通过管道传回给用户的方法。

#!/usr/bin/env node

var
    url = require('url'),
    http = require('http'),
    acceptor = http.createServer().listen(3128);

acceptor.on('request', function(request, response) {
    console.log('request ' + request.url);
    request.pause();
    var options = url.parse(request.url);
    options.headers = request.headers;
    options.method = request.method;
    options.agent = false;

    var connector = http.request(options);
    request.pipe(connector);
    request.resume();
//  connector.pipe(response); // doesn't work
//  connector.pipe(request); // doesn't work either
});

使用 tcpflow,我看到来自浏览器的传入请求,然后是传出代理请求,然后是服务器对代理的响应。不知何故,我无法将响应重新传输回浏览器。

用管道实现这个逻辑的正确方法是什么?

最佳答案

您不必“暂停”,只需“管道”即可

var connector = http.request(options, function(res) {
  res.pipe(response, {end:true});//tell 'response' end=true
});
request.pipe(connector, {end:true});

http 请求在你告诉它“结束”之前不会完成;

关于node.js - 通过将 http 服务器传送到 http 请求的简单 node.js 代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13472024/

相关文章:

javascript - 将 Javascript 参数传递给 Node.js

api - Flutter:接收数据时连接关闭

performance - 所有资源的 HSTS header ?或文件?

ubuntu - 如何在 Squid3 ubuntu 中记录完整的 URL?

php - 使用 Charles 和 SSL Apple 推送地址

node.js - 使用request和passport npm登录账号

node.js - Windows 路径上的 path.dirname 给出 `.`

nginx - Openshift - 内部 NGINX 代理无法连接到 Openshift 路由主机名

python - npm 使用 2 个版本的 Python

javascript - 我如何从本地主机 :5000 to localhost:3000 发送 http post 请求