Programing

node.js에서 간단한 http 프록시를 만드는 방법은 무엇입니까?

lottogame 2020. 12. 8. 07:35
반응형

node.js에서 간단한 http 프록시를 만드는 방법은 무엇입니까?


HTTP GET클라이언트에서 타사 웹 사이트 (예 : google)로 요청 을 전달하는 프록시 서버를 만들려고합니다 . 내 프록시는 수신 요청을 대상 사이트의 해당 경로로 미러링해야하므로 클라이언트의 요청 URL이 다음과 같은 경우 :

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 페이지에서 잘 작동하지만 다른 유형의 파일의 경우 대상 사이트에서 빈 페이지 또는 일부 오류 메시지 만 반환합니다 (사이트마다 다름).


타사 서버에서받은 응답을 처리하는 것은 좋지 않다고 생각합니다. 이렇게하면 프록시 서버의 메모리 공간 만 늘어납니다. 또한 코드가 작동하지 않는 이유입니다.

대신 클라이언트에 응답을 전달하십시오. 다음 스 니펫을 고려하십시오.

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-http-proxy은 nodejitsu에서 사용하는 구현 입니다.

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);

다음 은 리디렉션을 처리 하는 요청사용하는 프록시 서버 입니다. 프록시 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");
    }
}

이진 파일은 데이터 이벤트 처리기에서 문자열로 캐스트 할 수 없기 때문에 코드가 작동하지 않습니다. 바이너리 파일을 조작해야한다면 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();
});    

Super simple and readable, here's how you create a local proxy server to a local HTTP server with just Node.js (tested on v8.1.0). I've found it particular useful for integration testing so here's my share:

/**
 * 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);

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


I juste wrote a proxy in nodejs that take care of HTTPS with optional decoding of the message. This proxy also can add proxy-authentification header in order to go through a corporate proxy. You need to give as argument the url to find the proxy.pac file in order to configurate the usage of corporate proxy.

https://github.com/luckyrantanplan/proxy-to-proxy-https

참고URL : https://stackoverflow.com/questions/20351637/how-to-create-a-simple-http-proxy-in-node-js

반응형