programing

node.js http와 함께 http 프록시를 사용하려면 어떻게 해야 합니까?고객님?

i4 2023. 9. 3. 12:09
반응형

node.js http와 함께 http 프록시를 사용하려면 어떻게 해야 합니까?고객님?

HTTP를 js에서 .http.Client그러나 네트워크에서 직접 원격 서버에 연결할 수 없으므로 프록시를 사용해야 합니다.

node.js에게 프록시를 사용하도록 지시하려면 어떻게 해야 합니까?

맥팔레인대답은 HTTP 프록시 사용과 관련하여 가까웠습니다.

안전하지 않은 요청에 HTTP 프록시를 사용하는 것은 매우 간단합니다.경로 부분에 전체 URL이 포함되어 있고 호스트 헤더가 연결할 호스트로 설정되어 있는 경우를 제외하고 프록시에 연결하고 일반적으로 요청합니다.
팀은 그의 대답에 매우 가까웠지만 호스트 헤더를 제대로 설정하지 못했습니다.

var http = require("http");

var options = {
  host: "proxy",
  port: 8080,
  path: "http://www.google.com",
  headers: {
    Host: "www.google.com"
  }
};
http.get(options, function(res) {
  console.log(res);
  res.pipe(process.stdout);
});

그의 답변은 http://nodejs.org/ 에서 작동하지만, 그들의 서버는 호스트 헤더가 틀리다는 것을 신경 쓰지 않기 때문입니다.

편집: 2020년 2월 11일부터 요청이 완전히 사용되지 않습니다. 새 변경 사항이 필요하지 않습니다.

요청을 사용할 수 있습니다. 외부 "proxy" 매개 변수 하나만으로 node.js에서 프록시를 사용하는 것이 믿을 수 없을 정도로 쉽다는 것을 알게 되었습니다. 게다가 HTTP 프록시를 통해 HTTPS를 지원합니다.

var request = require('request');

request({
  'url':'https://anysite.you.want/sub/sub',
  'method': "GET",
  'proxy':'http://yourproxy:8087'
},function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body);
  }
})

https 서버에 프록시를 사용하려고 해도 'http'를 사용하여 프록시에 액세스하는 데 시간이 좀 걸렸습니다.이 기능은 Charles(osx 프로토콜 분석기)를 사용하여 작동합니다.

var http = require('http');

http.get ({
    host: '127.0.0.1',
    port: 8888,
    path: 'https://www.google.com/accounts/OAuthGetRequestToken'
}, function (response) {
    console.log (response);
});

개인 프록시 서버를 구입한 후 다음을 얻었습니다.

255.255.255.255 // IP address of proxy server
99999 // port of proxy server
username // authentication username of proxy server
password // authentication password of proxy server

그리고 저는 그것을 사용하고 싶었습니다.1차 답변과 2차 답변은 http(proxy) -> http(destination)만 가능했는데 http(proxy) -> https(destination)를 원했습니다.

그리고 https 목적지의 경우 HTTP 터널을 직접 사용하는 것이 좋습니다.여기서 해결책을 찾았습니다.

노드 v8:

const http = require('http')
const https = require('https')
const username = 'username'
const password = 'password'
const auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64')

http.request({
  host: '255.255.255.255', // IP address of proxy server
  port: 99999, // port of proxy server
  method: 'CONNECT',
  path: 'kinopoisk.ru:443', // some destination, add 443 port for https!
  headers: {
    'Proxy-Authorization': auth
  },
}).on('connect', (res, socket) => {
  if (res.statusCode === 200) { // connected to proxy server
    https.get({
      host: 'www.kinopoisk.ru',
      socket: socket,    // using a tunnel
      agent: false,      // cannot use a default agent
      path: '/your/url'  // specify path to get from server
    }, (res) => {
      let chunks = []
      res.on('data', chunk => chunks.push(chunk))
      res.on('end', () => {
        console.log('DONE', Buffer.concat(chunks).toString('utf8'))
      })
    })
  }
}).on('error', (err) => {
  console.error('error', err)
}).end()

노드 v14:

const http = require('http');
const https = require('https');
const username = 'username';
const password = 'password';
const auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');

http.request({
  host: '255.255.255.255', // IP address of proxy server
  port: 99999, // port of proxy server
  method: 'CONNECT',
  path: 'kinopoisk.ru:443', // some destination, add 443 port for https!
  headers: {
    'Proxy-Authorization': auth
  },
}).on('connect', (res, socket) => {
  if (res.statusCode === 200) { // connected to proxy server
    const agent = new https.Agent({ socket });
    https.get({
      host: 'www.kinopoisk.ru',
      path: '/',
      agent,      // cannot use a default agent
    }, (res) => {
      let chunks = []
      res.on('data', chunk => chunks.push(chunk))
      res.on('end', () => {
        console.log('DONE', Buffer.concat(chunks).toString('utf8'))
      })
    })
  }
}).on('error', (err) => {
  console.error('error', err)
}).end();

@Renat here에서 이미 언급했듯이, 프록시된 HTTP 트래픽은 상당히 일반적인 HTTP 요청으로 수신됩니다.대상의 전체 URL을 경로로 전달하여 프록시에 대해 요청합니다.

var http = require ('http');

http.get ({
    host: 'my.proxy.com',
    port: 8080,
    path: 'http://nodejs.org/'
}, function (response) {
    console.log (response);
});

제가 찾은 모듈을 추가하려고 생각했습니다. https://www.npmjs.org/package/global-tunnel, 은 저에게 아주 잘 작동했습니다. (아래 코드만 가지고 제 모든 코드와 타사 모듈에서 즉시 작동했습니다.)

require('global-tunnel').initialize({
  host: '10.0.0.10',
  port: 8080
});

이 작업을 한 번 수행하면 응용프로그램의 모든 http(및 https)가 프록시를 통과합니다.

또는 호출 중

require('global-tunnel').initialize();

합니다.http_proxy 변수

'request' http 패키지에는 다음과 같은 기능이 있습니다.

https://github.com/mikeal/request

예를 들어 아래의 'r' 요청 개체는 로컬 프록시를 사용하여 요청에 액세스합니다.

var r = request.defaults({'proxy':'http://localproxy.com'})

http.createServer(function (req, resp) {
  if (req.url === '/doodle.png') {
    r.get('http://google.com/doodle.png').pipe(resp)
  }
})

안타깝게도 "글로벌" 기본값은 없으므로 lib가 http 옵션을 통과하지 않는 한 이를 사용하는 lib 사용자는 프록시를 수정할 수 없습니다...

HTH, 크리스

프록시 공급자에 대한 기본 권한을 사용해야 하는 경우 다음을 사용합니다.

var http = require("http");

var options = {
    host:       FarmerAdapter.PROXY_HOST,
    port:       FarmerAdapter.PROXY_PORT,
    path:       requestedUrl,
    headers:    {
        'Proxy-Authorization':  'Basic ' + new Buffer(FarmerAdapter.PROXY_USER + ':' + FarmerAdapter.PROXY_PASS).toString('base64')
    }
};

var request = http.request(options, function(response) {
    var chunks = [];
    response.on('data', function(chunk) {
        chunks.push(chunk);
    });
    response.on('end', function() {
        console.log('Response', Buffer.concat(chunks).toString());
    });
});

request.on('error', function(error) {
    console.log(error.message);
});

request.end();

기본적으로 명시적인 프록시 지원은 필요하지 않습니다.프록시 프로토콜은 매우 간단하고 일반 HTTP 프로토콜을 기반으로 합니다.HTTP 클라이언트에 연결할 때 프록시 호스트와 포트를 사용하면 됩니다.예(node.js 문서에서):

var http = require('http');
var google = http.createClient(3128, 'your.proxy.host');
var request = google.request('GET', '/',
  {'host': 'www.google.com'});
request.end();
...

따라서 기본적으로 프록시에 연결하지만 "http://www.google.com "에 요청합니다.

노드는 http_proxy 환경 변수 사용을 지원해야 합니다. 따라서 노드는 교차 플랫폼이며 애플리케이션별 구성을 요구하지 않고 시스템 설정에서 작동합니다.

제공된 솔루션을 사용하여 다음을 권장합니다.

커피스크립트

get_url = (url, response) ->
  if process.env.http_proxy?
    match = process.env.http_proxy.match /^(http:\/\/)?([^:\/]+)(:([0-9]+))?/i
    if match
      http.get { host: match[2], port: (if match[4]? then match[4] else 80), path: url }, response
      return
  http.get url, response

자바스크립트

get_url = function(url, response) {
  var match;
  if (process.env.http_proxy != null) {
    match = process.env.http_proxy.match(/^(http:\/\/)?([^:\/]+)(:([0-9]+))?/i);
    if (match) {
      http.get({
        host: match[2],
        port: (match[4] != null ? match[4] : 80),
        path: url
      }, response);
      return;
    }
  }
  return http.get(url, response);
};

사용 방법을 사용하려면 http.get을 효과적으로 대체하십시오. 예를 들어, 다음은 구글의 인덱스 페이지를 test.htm이라는 파일에 씁니다.

file = fs.createWriteStream path.resolve(__dirname, "test.htm")
get_url "http://www.google.com.au/", (response) ->
  response.pipe file
  response.on "end", ->
    console.log "complete"

2019년 더 합니다. 2019년 12월 31일자로 답을 찾았습니다.우리는 사용할 수 있습니다.global-tunnel-ng 위한 입니다.http또는https모든 곳에 기반한 코드. 먼저설니다를 설치합니다.global-tunnel-ng패키지:

npm install global-tunnel-ng

그런 다음 필요한 경우 다음과 같이 프록시를 초기화하도록 구현을 변경합니다.

const globalTunnel = require('global-tunnel-ng');

globalTunnel.initialize({
  host: 'proxy.host.name.or.ip',
  port: 8080
});

다음과 같이 'session-session-agent'를 사용합니다.

var HttpsProxyAgent = require('https-proxy-agent');
var proxy = process.env.https_proxy || 'other proxy address';
var agent = new HttpsProxyAgent(proxy);

options = {
    //...
    agent : agent
}

https.get(options, (res)=>{...});

다음과 같은 프록시 래퍼를 사용하여 nodejs를 실행합니다.tsocks tsocks node myscript.js

원래 솔루션:NodeJS에서 SOCKS5 프록시를 통해 http 요청 수행

더 많은 정보: https://www.binarytides.com/proxify-applications-with-tsocks-and-proxychains-on-ubuntu/

창: https://superuser.com/questions/319516/how-to-force-any-program-to-use-socks

당신이 원하는 정확한 한 줄은 아닐 수도 있지만 http://github.com/nodejitsu/node-http-proxy 을 볼 수 있습니다. 그것이 당신의 앱을 http와 함께 사용하는 방법을 밝혀줄 수 있기 때문입니다.고객.

http://groups.google.com/group/nodejs/browse_thread/thread/d5aadbcaa00c3f7/12ebf01d7ec415c3?lnk=gst&q=proxy#12ebf01d7ec415c3

이 스레드의 답변을 보면 프록시 체인을 사용하여 프록시 서버를 통해 node.js를 실행할 수 있습니다.
$ proxychains /path/to/node application.js

개인적으로 Cygwin/Windows 환경에 프록시 체인 버전을 설치할 수 없어서 테스트할 수 없었습니다.

게다가 그들은 connect-proxy를 사용하는 것에 대해서도 이야기했지만, 나는 이것을 하는 방법에 대한 어떠한 문서도 찾을 수 없었습니다.

간단히 말해서, 저는 여전히 곤경에 처해 있지만, 누군가가 이 정보를 사용하여 적절한 해결책을 찾을 수 있을지도 모릅니다.

임스컬의 대답은 저에게 거의 효과가 있었지만, 저는 약간의 변화를 주어야 했습니다.유일한 실제 변경 사항은 사용자 이름, 암호를 추가하고 rejectUnauthorized를 false로 설정하는 것입니다.제가 댓글을 달지 못해서 이렇게 답변을 해드렸습니다.

코드를 실행하면 이 튜토리얼에 따라 해커 뉴스의 최신 기사 제목을 얻을 수 있습니다. http://smalljs.org/package-managers/npm/

var cheerio = require('cheerio');
var request = require('request');

request({
    'url': 'https://news.ycombinator.com/',
    'proxy': 'http://Username:Password@YourProxy:Port/',
    'rejectUnauthorized': false
}, function(error, response, body) {
    if (!error && response.statusCode == 200) {
        if (response.body) {
            var $ = cheerio.load(response.body);
            $('td.title a').each(function() {
                console.log($(this).text());
            });
       }
    } else {
        console.log('Error or status not equal 200.');
    }
});

환경 변수와 환경 변수만 설정합니다.http프록시를 사용합니다.

const env = {
    "host": "proxy.server.com.br",
    "port": 8080,
    "user": "my-user",
    "pass": "my-pass"
};

process.env.http_proxy =
  process.env.https_proxy =
    `http://${env.user}:${env.pass}@${env.host}:${env.port}/`;

Axios에는 문서에 프록시 옵션이 있습니다.또한 정의할 수 있습니다.http_proxy그리고.https_proxy환경 변수

// `proxy` defines the hostname, port, and protocol of the proxy server.
// You can also define your proxy using the conventional `http_proxy` and
// `https_proxy` environment variables. If you are using environment variables
// for your proxy configuration, you can also define a `no_proxy` environment
// variable as a comma-separated list of domains that should not be proxied.
// Use `false` to disable proxies, ignoring environment variables.
// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
// supplies credentials.
// This will set an `Proxy-Authorization` header, overwriting any existing
// `Proxy-Authorization` custom headers you have set using `headers`.
// If the proxy server uses HTTPS, then you must set the protocol to `https`. 

proxy: {
  protocol: 'https',
  host: '127.0.0.1',
  port: 9000,
  auth: {
    username: 'mikeymike',
    password: 'rapunz3l'
  }
},

만약 당신이 기본 http 인증 체계를 가지고 있다면 당신은 base64 문자열을 만들어야 합니다.myuser:mypassword처음에 "Basic"을 추가합니다. 값은 Proxy-Authorization 헤더 값입니다. 예는 다음과 같습니다.

var Http = require('http');

var req = Http.request({
    host: 'myproxy.com.zx',
    port: 8080,
    headers:{"Proxy-Authorization": "Basic bXl1c2VyOm15cGFzc3dvcmQ="},
    method: 'GET',
    path: 'http://www.google.com/'
    }, function (res) {
        res.on('data', function (data) {
        console.log(data.toString());
    });
});

req.end();

nodejs에서 버퍼를 사용하여 인코딩할 수 있습니다.

var encodedData = Buffer.from('myuser:mypassword').toString('base64');

console.log(encodedData);

예를 들어, 브라우저에서 btoa()를 사용하여 base64에서 인코딩할 수 있습니다. 이는 프록시 설정 없이 프록시를 사용하여 요청을 수행하는 브라우저의 Ajax 요청에 유용합니다.

var encodedData = btoa('myuser:mypassword')

console.log(encodedData);

프록시 서버를 허용하는 구성을 찾는 방법은 무엇입니까?

사용자 지정 DNS가 구성되지 않은 경우(ERR_NAME_NOT_RESOLVED와 같은 항목이 발생할 수 있음), 요청을 수행할 때 응답(코드 407)은 프록시가 사용 중인 http 인증 체계를 응답 헤더에 알려야 합니다.

언급URL : https://stackoverflow.com/questions/3862813/how-can-i-use-an-http-proxy-with-node-js-http-client

반응형