次の方法で共有


Node.js アプリケーションで開発プロキシを使用する

Node.js アプリケーションのプロキシを有効にする標準的な方法はありません。 プロキシを使用できるかどうかは、HTTP 要求を行うために使用しているライブラリによって異なります。 通常は、プロキシを構成するためにコードを更新する必要があります。 ただし、 global-agent パッケージを使用して、最小限のコード変更でNode.js アプリケーションのプロキシ サポートを有効にすることができます。

ネイティブ Node.js フェッチ API

v17.5.0 では、Node.jsでは、 fetch API の試験的なサポートが導入されています。 残念ながら、この API はまだ制限されており、プロキシの構成はサポートされていません。 Node.jsで開発プロキシを使用する場合は、HTTP 要求を行うために別のライブラリを使用する必要があります。

global-agent

global-agent は、Node.js用のグローバル HTTP/HTTPS エージェントを提供する一般的なライブラリです。 これにより、環境変数を使用してプロキシを指定できます。 global-agentを使用する利点は、開発プロキシを使用するためにアプリケーションで HTTP 要求を発行する方法を変更する必要がないようにすることです。

node-fetchを使用するNode.js アプリケーションでglobal-agentを使用する方法の例を次に示します。

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

Node.jsと標準のhttps モジュールでglobal-agentを使用する方法を次に示します。

const https = require('https');
const globalAgent = require('global-agent');
globalAgent.bootstrap();

https.get('https://jsonplaceholder.typicode.com/posts', (resp) => {
  let data = '';
  resp.on('data', (d) => {
    data += d;
  });
  resp.on('end', () => {
    console.log(JSON.parse(data));
  });
  resp.on('error', (err) => {
    console.error(err);
  });
});

アプリケーションを起動するときに、 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 メソッドに渡す必要があります。

https-proxy-agent パッケージを使用してエージェントを定義することで、開発プロキシでnode-fetchを使用する方法の例を次に示します。

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 要求を行うもう 1 つの一般的なライブラリです。 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-fetchと同様に、Got では、環境変数を使用したプロキシの指定はサポートされていません。 代わりに、カスタム エージェントを作成し、それを要求に渡す必要があります。

開発プロキシで 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