如何在node.js中创建一个简单的http代理?

Nas*_*ade 59 javascript proxy node.js

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

127.0.0.1/images/srpr/logo11w.png
Run Code Online (Sandbox Code Playgroud)

应提供以下资源:

http://www.google.com/images/srpr/logo11w.png
Run Code Online (Sandbox Code Playgroud)

这是我想出的:

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();
    });
}
Run Code Online (Sandbox Code Playgroud)

它适用于html页面,但对于其他类型的文件,它只返回一个空白页面或来自目标站点的一些错误消息(在不同的站点中有所不同).

vmx*_*vmx 78

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

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

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
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,您需要维护内容类型标头.HTML数据的工作原理正如您所提到的,因为内容类型默认为`text/html`,对于images/pdf或任何其他内容,确保您传递正确的标题.如果您分享您对回复所应用的修改,我将能够提供更多帮助. (3认同)
  • 你不应该使用代理模块:https://github.com/nodejitsu/node-http-proxy? (3认同)

bos*_*ood 22

这是使用node-http-proxynodejitsu 的实现.

var http = require('http');
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});

http.createServer(function(req, res) {
    proxy.web(req, res, { target: 'http://www.google.com' });
}).listen(3000);
Run Code Online (Sandbox Code Playgroud)

  • 我认为node-http-proxy主要用于反向代理...,从外部客户端到运行在本地IP上的内部服务器和非标准端口,通过反向节点代理接受公共IP地址上标准端口上的连接. (3认同)

Hen*_*nry 11

这是使用处理重定向的请求的代理服务器.通过点击您的代理URL http://domain.com:3000/?url=[your_url]来使用它

var http = require('http');
var url = require('url');
var request = require('request');

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

function onRequest(req, res) {

    var queryData = url.parse(req.url, true).query;
    if (queryData.url) {
        request({
            url: queryData.url
        }).on('error', function(e) {
            res.end(e);
        }).pipe(res);
    }
    else {
        res.end("no url found");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 嗨亨利,如何为请求添加标头? (4认同)

Fra*_*ula 7

超级简单易读,以下是如何使用 Node.js(在v8.1.0 上测试)创建本地代理服务器到本地 HTTP 服务器。我发现它对集成测试特别有用,所以这是我的分享:

/**
 * Once this is running open your browser and hit http://localhost
 * You'll see that the request hits the proxy and you get the HTML back
 */

'use strict';

const net = require('net');
const http = require('http');

const PROXY_PORT = 80;
const HTTP_SERVER_PORT = 8080;

let proxy = net.createServer(socket => {
    socket.on('data', message => {
        console.log('---PROXY- got message', message.toString());

        let serviceSocket = new net.Socket();

        serviceSocket.connect(HTTP_SERVER_PORT, 'localhost', () => {
            console.log('---PROXY- Sending message to server');
            serviceSocket.write(message);
        });

        serviceSocket.on('data', data => {
            console.log('---PROXY- Receiving message from server', data.toString();
            socket.write(data);
        });
    });
});

let httpServer = http.createServer((req, res) => {
    switch (req.url) {
        case '/':
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end('<html><body><p>Ciao!</p></body></html>');
            break;
        default:
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end('404 Not Found');
    }
});

proxy.listen(PROXY_PORT);
httpServer.listen(HTTP_SERVER_PORT);
Run Code Online (Sandbox Code Playgroud)

https://gist.github.com/fracasula/d15ae925835c636a5672311ef584b999


小智 6

这是上面 Mike 回答的更优化版本,它正确获取网站内容类型,支持 POST 和 GET 请求,并使用您的浏览器用户代理,以便网站可以将您的代理识别为浏览器。您可以通过更改简单地设置 URL url =,它会自动设置 HTTP 和 HTTPS 内容,而无需手动设置。

var express = require('express')
var app = express()
var https = require('https');
var http = require('http');
const { response } = require('express');


app.use('/', function(clientRequest, clientResponse) {
    var url;
    url = 'https://www.google.com'
    var parsedHost = url.split('/').splice(2).splice(0, 1).join('/')
    var parsedPort;
    var parsedSSL;
    if (url.startsWith('https://')) {
        parsedPort = 443
        parsedSSL = https
    } else if (url.startsWith('http://')) {
        parsedPort = 80
        parsedSSL = http
    }
    var options = { 
      hostname: parsedHost,
      port: parsedPort,
      path: clientRequest.url,
      method: clientRequest.method,
      headers: {
        'User-Agent': clientRequest.headers['user-agent']
      }
    };  
  
    var serverRequest = parsedSSL.request(options, function(serverResponse) { 
      var body = '';   
      if (String(serverResponse.headers['content-type']).indexOf('text/html') !== -1) {
        serverResponse.on('data', function(chunk) {
          body += chunk;
        }); 
  
        serverResponse.on('end', function() {
          // Make changes to HTML files when they're done being read.
          body = body.replace(`example`, `Cat!` );
  
          clientResponse.writeHead(serverResponse.statusCode, serverResponse.headers);
          clientResponse.end(body);
        }); 
      }   
      else {
        serverResponse.pipe(clientResponse, {
          end: true
        }); 
        clientResponse.contentType(serverResponse.headers['content-type'])
      }   
    }); 
  
    serverRequest.end();
  });    


  app.listen(3000)
  console.log('Running on 0.0.0.0:3000')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

在此处输入图片说明


小智 5

您的代码不适用于二进制文件,因为它们无法在数据事件处理程序中转换为字符串。如果您需要操作二进制文件,则需要使用buffer。抱歉,我没有使用缓冲区的示例,因为就我而言,我需要操作 HTML 文件。我只是检查内容类型,然后根据需要更新文本/html 文件:

app.get('/*', function(clientRequest, clientResponse) {
  var options = { 
    hostname: 'google.com',
    port: 80, 
    path: clientRequest.url,
    method: 'GET'
  };  

  var googleRequest = http.request(options, function(googleResponse) { 
    var body = ''; 

    if (String(googleResponse.headers['content-type']).indexOf('text/html') !== -1) {
      googleResponse.on('data', function(chunk) {
        body += chunk;
      }); 

      googleResponse.on('end', function() {
        // Make changes to HTML files when they're done being read.
        body = body.replace(/google.com/gi, host + ':' + port);
        body = body.replace(
          /<\/body>/, 
          '<script src="http://localhost:3000/new-script.js" type="text/javascript"></script></body>'
        );

        clientResponse.writeHead(googleResponse.statusCode, googleResponse.headers);
        clientResponse.end(body);
      }); 
    }   
    else {
      googleResponse.pipe(clientResponse, {
        end: true
      }); 
    }   
  }); 

  googleRequest.end();
});    
Run Code Online (Sandbox Code Playgroud)