Node.js에서 프록시 만들기

WBOY
풀어 주다: 2023-08-24 21:41:05
앞으로
1210명이 탐색했습니다.

在 Node.js 中创建代理

새로운 Agent() 메소드를 사용하여 Node.js에서 에이전트 인스턴스를 생성할 수 있습니다. http.request() 메소드는 "http" 모듈의 globalAgent를 사용하여 사용자 정의 http.Agent 인스턴스를 생성합니다.

Syntax

new Agent({options})
로그인 후 복사

Parameters

위 함수는 다음 Parameters

  • Options< /strong>을 허용할 수 있습니다. - 이러한 옵션에는 생성 시 에이전트에 설정할 수 있는 구성 가능한 옵션이 포함됩니다. 프록시가 가질 수 있는 필드/옵션은 다음과 같습니다. -

    • keepAlive - 이 방법은 미해결 요청이 있는지 여부에 관계없이 소켓을 유지하지만 실제로 TCP 연결을 다시 설정하지 않고 향후 요청에 대해 소켓을 유지합니다. 이 연결은 "연결 닫기"를 사용하여 닫을 수 있습니다. 기본값: 거짓.

    • keepAliveMsecs - 이 옵션은 keepAlive 옵션이 true로 설정된 경우 TCP 연결 유지 패킷의 초기 지연을 정의합니다. 기본값은 1000입니다.

    • maxSockets - 이 옵션은 호스트당 허용되는 최대 소켓 수를 정의합니다. 기본적으로 이 값은 무한대입니다.

    • maxTotalSockets – 모든 호스트에서 허용되는 총 소켓 수입니다. 각 요청은 한도에 도달할 때까지 새 소켓을 사용합니다. 기본값은 무한대입니다.

    • maxFreeSockets - 유휴 상태에서 열어둘 수 있는 최대 여유 소켓 수입니다. 기본값은 256입니다.

    • Scheduling - 사용할 다음 여유 소켓을 선택할 때 적용할 수 있는 스케줄링 전략입니다. 일정은 "fifo" 또는 "lifo"일 수 있습니다.

    • timeout - 소켓 시간 초과를 밀리초 단위로 나타냅니다.

예제

agent.js라는 파일을 만들고 다음 코드 조각을 복사하세요. 파일을 생성한 후 아래 예에 표시된 대로 다음 명령을 사용하여 이 코드를 실행합니다. -

node agent.js
로그인 후 복사

agent.js

라이브 데모

// Node.js program to demonstrate the creation of new Agent

// Importing the http module
const http = require(&#39;http&#39;);

// Creating a new agent
var agent = new http.Agent({});

// Defining options for agent
const aliveAgent = new http.Agent({
   keepAlive: true, maxSockets: 5,
});

// Creating connection with alive agent
var aliveConnection = aliveAgent.createConnection;

// Creating new connection
var connection = agent.createConnection;

// Printing the connection
console.log(&#39;Succesfully created connection with agent: &#39;,
connection.toString);
console.log(&#39;Succesfully created connection with alive agent: &#39;,
aliveConnection.toString);
로그인 후 복사

Output

C:\homeode>> node agent.js
Succesfully created connection with agent: function toString() { [native code] }
Succesfully created connection with alive agent: function toString() { [native code] }
로그인 후 복사

Example

"agentkeepalive" 모듈이 생성을 시도 중입니다. 소켓이나 에이전트는 더 나은 유연성을 제공합니다. 더 나은 이해를 위해 다음 예에서 이 모듈을 사용하겠습니다.

설치

npm install agentkeepalive --save
로그인 후 복사

프로그램 코드

// Node.js program to demonstrate the creation of new Agent

// Importing the http module
const http = require(&#39;http&#39;);
// Importing the agentkeepalive module
const Agent = require(&#39;agentkeepalive&#39;);

// Creating a new agent
const keepAliveAgent = new Agent({});

// Implementing some options
const options = {
   host: &#39;tutorialspoint.com&#39;,
   port: 80,
   path: &#39;/&#39;,
   method: &#39;GET&#39;,
   agent: keepAliveAgent,
};

// Requesting details via http server module
const req = http.request(options, (res) => {
   // Printing statuscode, headers and other details
   // received from the request
   console.log("StatusCode: ", res.statusCode);
   console.log("Headers: ", res.headers);
});

// Printing the agent options
console.log("Agent Options: ", req.agent.options);
req.end();
로그인 후 복사

출력

C:\homeode>> node agent.js
Agent Options: { socketActiveTTL: 0,
   timeout: 30000,
   freeSocketTimeout: 15000,
   keepAlive: true,
   path: null }
StatusCode: 403
Headers: { date: &#39;Sun, 25 Apr 2021 08:21:14 GMT&#39;,
   server: &#39;Apache&#39;,
   &#39;x-frame-options&#39;: &#39;SAMEORIGIN&#39;,
   &#39;last-modified&#39;: &#39;Thu, 16 Oct 2014 13:20:58 GMT&#39;,
   etag: &#39;"1321-5058a1e728280"&#39;,
   &#39;accept-ranges&#39;: &#39;bytes&#39;,
   &#39;content-length&#39;: &#39;4897&#39;,
   &#39;x-xss-protection&#39;: &#39;1; mode=block&#39;,
   vary: &#39;User-Agent&#39;,
   &#39;keep-alive&#39;: &#39;timeout=5, max=100&#39;,
   connection: &#39;Keep-Alive&#39;,
   &#39;content-type&#39;: &#39;text/html; charset=UTF-8&#39; }
로그인 후 복사

위 내용은 Node.js에서 프록시 만들기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:tutorialspoint.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!