如何在 node.js 中创建一个简单的 http 代理? [英] How to create a simple http proxy in node.js?

查看:68
本文介绍了如何在 node.js 中创建一个简单的 http 代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个代理服务器来将 HTTP GET 请求从客户端传递到第三方网站(比如谷歌).我的代理只需要将传入请求镜像到目标站点上的相应路径,因此如果我的客户端请求的 url 是:

I'm trying to create a proxy server to pass HTTP GET requests from a client to a third party website (say google). My proxy just needs to mirror incoming requests to their corresponding path on the target site, so if my client's requested url is:

127.0.0.1/images/srpr/logo11w.png

应提供以下资源:

http://www.google.com/images/srpr/logo11w.png

这是我想出的:

http.createServer(onRequest).listen(80);

function onRequest (client_req, client_res) {
    client_req.addListener("end", function() {
        var options = {
            hostname: 'www.google.com',
            port: 80,
            path: client_req.url,
            method: client_req.method
            headers: client_req.headers
        };
        var req=http.request(options, function(res) {
            var body;
            res.on('data', function (chunk) {
                body += chunk;
            });
            res.on('end', function () {
                 client_res.writeHead(res.statusCode, res.headers);
                 client_res.end(body);
            });
        });
        req.end();
    });
}

它适用于 html 页面,但对于其他类型的文件,它只会返回一个空白页面或来自目标站点的一些错误消息(因站点而异).

It works well with html pages, but for other types of files, it just returns a blank page or some error message from target site (which varies in different sites).

推荐答案

我认为处理从 3rd 方服务器收到的响应不是一个好主意.这只会增加代理服务器的内存占用.此外,这也是您的代码无法正常工作的原因.

I don't think it's a good idea to process response received from the 3rd party server. This will only increase your proxy server's memory footprint. Further, it's the reason why your code is not working.

而是尝试将响应传递给客户端.考虑以下片段:

Instead try passing the response through to the client. Consider following snippet:

var http = require('http');

http.createServer(onRequest).listen(3000);

function onRequest(client_req, client_res) {
  console.log('serve: ' + client_req.url);

  var options = {
    hostname: 'www.google.com',
    port: 80,
    path: client_req.url,
    method: client_req.method,
    headers: client_req.headers
  };

  var proxy = http.request(options, function (res) {
    client_res.writeHead(res.statusCode, res.headers)
    res.pipe(client_res, {
      end: true
    });
  });

  client_req.pipe(proxy, {
    end: true
  });
}

这篇关于如何在 node.js 中创建一个简单的 http 代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆