다음을 통해 공유


Node.js 애플리케이션에서 개발 프록시 사용

Node.js 애플리케이션에 프록시를 사용하도록 설정하는 표준 방법은 없습니다. 프록시를 사용할 수 있는지 여부는 HTTP 요청을 만드는 데 사용하는 라이브러리에 따라 달라집니다. 일반적으로 프록시를 구성하려면 코드를 업데이트해야 합니다. 그러나 패키지를 사용하여 global-agent 최소한의 코드 변경으로 Node.js 애플리케이션에 대한 프록시 지원을 사용하도록 설정할 수 있습니다.

네이티브 Node.js 가져오기 API

v17.5.0에서 Node.js API에 대한 fetch 실험적 지원을 도입합니다. 아쉽게도 이 API는 여전히 제한되어 있으며 프록시 구성을 지원하지 않습니다. Node.js 함께 개발 프록시를 사용하려면 HTTP 요청을 만들기 위해 다른 라이브러리를 사용해야 합니다.

global-agent

global-agent 는 Node.js 전역 HTTP/HTTPS 에이전트를 제공하는 인기 있는 라이브러리입니다. 환경 변수를 사용하여 프록시를 지정할 수 있습니다. 를 사용하면 global-agent 애플리케이션에서 개발자 프록시를 사용하도록 HTTP 요청을 발급하는 방법을 변경할 필요가 없다는 이점이 있습니다.

다음은 를 사용하는 Node.js 애플리케이션에서 사용할 global-agent 수 있는 방법의 예입니다. node-fetch

import fetch from 'node-fetch';
import { bootstrap } from 'global-agent';
bootstrap();

(async () => {
  const result = await fetch('https://jsonplaceholder.typicode.com/posts');
  const jsonResult = await result.json();
  console.log(JSON.stringify(jsonResult, null, 2));
})();

애플리케이션을 시작할 때 환경 변수를 사용하여 프록시를 GLOBAL_AGENT_HTTP_PROXY 지정하고 인증서 오류를 무시합니다.

NODE_TLS_REJECT_UNAUTHORIZED=0 GLOBAL_AGENT_HTTP_PROXY=http://127.0.0.1:8000 node global-node-fetch.mjs

node-fetch

node-fetch 는 Node.js 구현을 fetch 제공하는 인기 있는 라이브러리입니다. node-fetch 는 환경 변수를 사용하여 프록시를 지정하는 것을 지원하지 않습니다. 대신 사용자 지정 에이전트를 만들고 메서드에 fetch 전달해야 합니다.

다음은 패키지를 사용하여 에이전트를 정의하여 개발자 프록시와 함께 사용할 node-fetch 수 있는 방법의 예입니다 https-proxy-agent .

const fetch = require('node-fetch');
const { HttpsProxyAgent } = require('https-proxy-agent');

(async () => {
  // Create a custom agent pointing to Dev Proxy
  const agent = new HttpsProxyAgent('http://127.0.0.1:8000');
  // Pass the agent to the fetch method
  const result = await fetch('https://jsonplaceholder.typicode.com/posts', { agent });
  const jsonResult = await result.json();
  console.log(JSON.stringify(jsonResult, null, 2));
})();

Axios

Axios 는 Node.js HTTP 요청을 만들기 위한 또 다른 인기 있는 라이브러리입니다. Axios를 사용하면 환경 변수를 사용하여 프록시를 지정하거나 요청 구성에서 에이전트를 직접 지정할 수 있습니다.

환경 변수와 함께 Axios 및 개발자 프록시 사용

Axios에서 개발 프록시를 사용하고 환경 변수를 사용하여 프록시를 지정하는 경우 코드를 변경할 필요가 없습니다. 환경 변수를 설정 https_proxy 하기만 하면 Axios에서 이를 사용하여 요청을 수행할 수 있습니다.

import axios from 'axios';

(async () => {
  const result = await axios.get('https://jsonplaceholder.typicode.com/posts');
  const response = result.data;
  console.log(JSON.stringify(response, null, 2));
})();

https_proxy 전역적으로 또는 앱을 시작할 때 환경 변수를 지정합니다.

https_proxy=http://127.0.0.1:8000 node axios.mjs

있어

과 유사하게 node-fetchGot는 환경 변수를 사용하여 프록시를 지정하는 것을 지원하지 않습니다. 대신 사용자 지정 에이전트를 만들어 요청에 전달해야 합니다.

개발자 프록시에서 Got를 사용하는 방법의 예는 다음과 같습니다.

import got from 'got';
import { HttpsProxyAgent } from 'https-proxy-agent';

(async () => {
  // Create a custom agent pointing to Dev Proxy
  const agent = new HttpsProxyAgent('http://127.0.0.1:8000');
  const result = await got('https://jsonplaceholder.typicode.com/posts', {
    // Pass the agent to the fetch method
    agent: {
      https: agent
    },
    // Disable certificate validation
    https: {
      rejectUnauthorized: false
    }
  }).json();
  console.log(JSON.stringify(result, null, 2));
})();

SuperAgent

SuperAgent 는 환경 변수를 사용하여 프록시를 지정하는 것을 지원하지 않습니다. SuperAgent와 함께 개발 프록시를 사용하려면 플러그 인을 superagent-proxy 설치하고 메서드를 사용하여 프록시를 proxy 구성해야 합니다.

const superagent = require('superagent');
require('superagent-proxy')(superagent);

(async () => {
  const result = await superagent
    .get('https://jsonplaceholder.typicode.com/posts')
    .proxy('http://127.0.0.1:8000')
    // Disable certificate validation
    .disableTLSCerts();
  console.log(JSON.stringify(result.body, null, 2));
})();

알려진 문제

Node.js 개발자 프록시를 사용하는 경우 다음과 같은 문제가 발생할 수 있습니다.

UNABLE_TO_VERIFY_LEAF_SIGNATURE개 오류

Node.js 함께 개발 프록시를 사용하는 경우 다음과 유사한 오류가 발생합니다.

/Users/user/my-app/node_modules/node-fetch/lib/index.js:1501
                        reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
                               ^
FetchError: request to https://jsonplaceholder.typicode.com/posts failed, reason: unable to verify the first certificate
    at ClientRequest.<anonymous> (/Users/user/my-app/node_modules/node-fetch/lib/index.js:1501:11)
    at ClientRequest.emit (node:events:518:28)
    at TLSSocket.socketErrorListener (node:_http_client:495:9)
    at TLSSocket.emit (node:events:518:28)
    at emitErrorNT (node:internal/streams/destroy:169:8)
    at emitErrorCloseNT (node:internal/streams/destroy:128:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  type: 'system',
  errno: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
  code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'
}

이 문제를 해결하려면 환경 변수를 로 NODE_TLS_REJECT_UNAUTHORIZED 설정해야 합니다 0. 전역적으로 정의하거나 앱을 시작할 때 인라인으로 정의할 수 있습니다.

NODE_TLS_REJECT_UNAUTHORIZED=0 node index.js