Node.js:通过 socks-proxy-agent 发起请求
更新于 2026-09-21
为 Node.js HTTPS 请求设置 SOCKS5 Agent,处理密码编码与超时。
准备条件
使用受支持的 Node.js 版本,在项目目录安装依赖。以下脚本保存为 .mjs 文件,使用 Node 内置 https 模块,不是浏览器 JavaScript。
npm install socks-proxy-agent
配置与请求
在本机私有运行配置中提供 SF_PROXY_HOST、SF_PROXY_PORT、SF_PROXY_USER、SF_PROXY_PASSWORD 四个环境变量。密码不要提交到代码仓库。
import https from 'node:https';
import { SocksProxyAgent } from 'socks-proxy-agent';
const { SF_PROXY_HOST: host, SF_PROXY_PORT: port,
SF_PROXY_USER: user, SF_PROXY_PASSWORD: password } = process.env;
if (!host || !port || !user || !password) throw new Error('缺少代理配置');
const proxy = new URL('socks5h://127.0.0.1');
proxy.hostname = host;
proxy.port = port;
proxy.username = encodeURIComponent(user);
proxy.password = encodeURIComponent(password);
const agent = new SocksProxyAgent(proxy);
const req = https.get('https://api.ipify.org', { agent }, res => {
if (res.statusCode !== 200) {
console.error('出口查询未成功:', res.statusCode);
res.resume();
return;
}
res.setEncoding('utf8');
res.on('data', chunk => process.stdout.write(chunk));
});
const timer = setTimeout(() => req.destroy(new Error('请求超时')), 30000);
req.on('close', () => clearTimeout(timer));
req.on('error', () => console.error('连接失败,请核对代理和网络'));
验证成功
确认返回出口与商品类型相符。每个需要代理的 https 请求都要使用该 Agent;只创建 Agent 而不传给请求不会生效。
常见问题
Node 原生 fetch 不使用 https.Agent,不能直接把此示例的 agent 参数移植给 fetch。若使用其他请求库,先确认它支持哪一种代理接口。不要通过忽略证书错误解决代理连接失败。
