将 Dev Proxy 用于 Node.js 应用程序

概览
目标: 将 Node.js 应用程序配置为使用开发代理
时间: 10 分钟
先决条件:设置开发代理,Node.js 应用程序

如何通过开发代理路由 Node.js 请求取决于 Node.js 版本和用于发出 HTTP 请求的库。 最近的 Node.js 版本可以通过环境变量中定义的代理路由本机 fetch API 以及 http 和 https 模块。 对于较旧的 Node.js 版本以及对于其他库,请在代码中配置代理,或使用 global-agent 包在仅需极少代码更改的情况下启用代理支持。

无论使用哪种方法,Node.js 都必须信任开发代理根证书,才能通过开发代理发出 HTTPS 请求。 有关详细信息,请参阅 信任开发代理证书。

信任开发代理证书

Node.js 默认情况下不使用操作系统证书存储,因此即使在计算机上信任 Dev Proxy 根证书,也不会信任该证书。 不要禁用证书验证,而应使用 NODE_EXTRA_CA_CERTS 环境变量将开发代理根证书添加到 Node.js 信任的证书中。

NODE_EXTRA_CA_CERTS 需要 PEM 格式的证书。 在开发代理运行时,使用 devproxy api token 获取 API 令牌,并使用 Dev Proxy API 以 PEM 格式下载根证书:

TOKEN=$(devproxy api token)
curl -H "Authorization: Bearer $TOKEN" -o dev-proxy-ca.pem "http://127.0.0.1:8897/proxy/rootCertificate?format=crt"

如果使用 PowerShell,请运行:

$token = devproxy api token
Invoke-WebRequest -Headers @{ Authorization = "Bearer $token" } -OutFile dev-proxy-ca.pem -Uri "http://127.0.0.1:8897/proxy/rootCertificate?format=crt"

然后,在启动应用时将 NODE_EXTRA_CA_CERTS 环境变量指向下载的文件:

NODE_EXTRA_CA_CERTS=./dev-proxy-ca.pem node index.js

Node.js 仅在进程启动时读取 NODE_EXTRA_CA_CERTS ,因此无法从代码中设置它。 每个 Dev Proxy 安装都使用自己的根证书。 如果重新创建证书,例如使用 devproxy cert remove 和 devproxy cert ensure,请再次下载证书。

本机 Node.js 提取 API

从 Node.js v24.0.0 和 v22.21.0 开始,原生 fetch API 可以使用在 HTTPS_PROXY、NO_PROXY 和 HTTP_PROXY 环境变量中定义的代理。 从 Node.js v24.5.0 和 v22.21.0 开始,这同样适用于 http 和 https 模块。 Node.js 忽略这些变量,除非通过将环境变量1设置为NODE_USE_ENV_PROXY或使用标志启动 Node.js --use-env-proxy 来启用代理支持。

无需更改代码,即可将开发代理与原生 fetch API 配合使用:

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

启动应用时,启用代理支持,将开发代理指定为代理,并信任开发代理根证书:

NODE_USE_ENV_PROXY=1 HTTPS_PROXY=http://127.0.0.1:8000 HTTP_PROXY=http://127.0.0.1:8000 NODE_EXTRA_CA_CERTS=./dev-proxy-ca.pem node index.js

或者,使用 --use-env-proxy 标志而不是 NODE_USE_ENV_PROXY 环境变量:

HTTPS_PROXY=http://127.0.0.1:8000 HTTP_PROXY=http://127.0.0.1:8000 NODE_EXTRA_CA_CERTS=./dev-proxy-ca.pem node --use-env-proxy index.js

注意

内置代理支持在 Node.js中处于积极开发状态。 若要检查 Node.js 版本是否支持它,请运行 node --version。 如果使用较旧版本,请使用 undici 包或 global-agent 包,如以下部分所述。

将原生 fetch API 与较旧的 Node.js 版本配合使用

如果你使用的 Node.js 版本不支持 NODE_USE_ENV_PROXY,请使用来自 undici 包的 EnvHttpProxyAgent,该包在 Node.js 中实现了原生 fetch API。 EnvHttpProxyAgent 从 HTTP_PROXY、HTTPS_PROXY 和 NO_PROXY 环境变量中读取代理。 在应用开始时将其设置为全局调度程序:

import { EnvHttpProxyAgent, setGlobalDispatcher } from 'undici';
setGlobalDispatcher(new EnvHttpProxyAgent());

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

启动应用时,将开发代理指定为代理并信任开发代理根证书:

HTTPS_PROXY=http://127.0.0.1:8000 HTTP_PROXY=http://127.0.0.1:8000 NODE_EXTRA_CA_CERTS=./dev-proxy-ca.pem node index.mjs

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

下面介绍了如何将global-agent与 Node.js 和标准https模块一起使用:

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_EXTRA_CA_CERTS=./dev-proxy-ca.pem 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));
})();

启动应用时, 信任开发代理根证书:

NODE_EXTRA_CA_CERTS=./dev-proxy-ca.pem node index.js

Axios

Axios 是另一个常用库,用于在 Node.js 中发出 HTTP 请求。 Axios 允许使用环境变量指定代理,或直接在请求配置中指定 agent。

将 Axios 和开发代理与环境变量配合使用

将 Dev Proxy 与 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_EXTRA_CA_CERTS=./dev-proxy-ca.pem 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 request
    agent: {
      https: agent
    }
  }).json();
  console.log(JSON.stringify(result, null, 2));
})();

启动应用时, 信任开发代理根证书:

NODE_EXTRA_CA_CERTS=./dev-proxy-ca.pem node got.mjs

SuperAgent

SuperAgent 不支持使用环境变量指定代理。 若要将 Dev Proxy 与 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');
  console.log(JSON.stringify(result.body, null, 2));
})();

启动应用时, 信任开发代理根证书:

NODE_EXTRA_CA_CERTS=./dev-proxy-ca.pem node superagent.js

已知问题

将 Dev Proxy 用于 Node.js 时,可能会遇到以下问题。

UNABLE_TO_VERIFY_LEAF_SIGNATURE 错误

将 Dev Proxy 与 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.js 不信任开发代理根证书。 若要解决此问题,请下载 Dev Proxy 根证书,并在启动应用时将 NODE_EXTRA_CA_CERTS 环境变量设置为下载的文件的路径。 有关详细信息,请参阅 信任开发代理证书。

NODE_EXTRA_CA_CERTS=./dev-proxy-ca.pem node index.js

Warning

避免将 NODE_TLS_REJECT_UNAUTHORIZED 设置为 0 以绕过此错误。 它禁用应用发出的所有 HTTPS 请求的证书验证。

另请参阅