示例
【Example】
要启动一个 Node.js 进程,并为通过默认全局代理发送的所有请求启用代理支持,可以使用 NODE_USE_ENV_PROXY 环境变量:
【To start a Node.js process with proxy support enabled for all requests sent
through the default global agent, either use the NODE_USE_ENV_PROXY environment
variable:】
NODE_USE_ENV_PROXY=1 HTTP_PROXY=http://proxy.example.com:8080 NO_PROXY=localhost,127.0.0.1 node client.js 或者使用 --use-env-proxy 参数。
【Or the --use-env-proxy flag.】
HTTP_PROXY=http://proxy.example.com:8080 NO_PROXY=localhost,127.0.0.1 node --use-env-proxy client.js 要创建具有内置代理支持的自定义代理:
【To create a custom agent with built-in proxy support:】
const http = require('node:http');
// Creating a custom agent with custom proxy support.
const agent = new http.Agent({ proxyEnv: { HTTP_PROXY: 'http://proxy.example.com:8080' } });
http.request({
hostname: 'www.example.com',
port: 80,
path: '/',
agent,
}, (res) => {
// This request will be proxied through proxy.example.com:8080 using the HTTP protocol.
console.log(`STATUS: ${res.statusCode}`);
}); 或者,以下方法也有效:
【Alternatively, the following also works:】
const http = require('node:http');
// Use lower-cased option name.
const agent1 = new http.Agent({ proxyEnv: { http_proxy: 'http://proxy.example.com:8080' } });
// Use values inherited from the environment variables, if the process is started with
// HTTP_PROXY=http://proxy.example.com:8080 this will use the proxy server specified
// in process.env.HTTP_PROXY.
const agent2 = new http.Agent({ proxyEnv: process.env });