You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Socks5代理浏览器可用但Node.js无法访问内网API问题求助

问题原因

你的Node.js脚本出现ENOTFOUND intranet.mycompany.com错误,核心是本地DNS无法解析公司内网域名:浏览器的系统代理会自动让DNS请求走SOCKS代理(由办公Mac的DNS解析内网域名),但Node.js默认在本地解析域名,而本地DNS不知道内网域名的对应IP,导致解析失败。

解决方案

1. 用socks5h协议修正代理配置

SOCKS5有两种模式,关键区别在DNS解析逻辑:

  • socks5://:本地解析域名,再把IP发给代理
  • socks5h://:把域名直接发给代理,由办公Mac(处于公司VPN内)负责解析DNS

方法A:环境变量实现全局代理

运行Node脚本前设置临时环境变量(终端关闭后失效):

export http_proxy=socks5h://localhost:9999
export https_proxy=socks5h://localhost:9999

之后直接运行脚本即可,所有HTTP/HTTPS请求(包括node-fetch和https模块)会自动走代理,DNS解析由办公Mac完成。

也可以一次性在命令行附带环境变量:

http_proxy=socks5h://localhost:9999 https_proxy=socks5h://localhost:9999 node your-fetch-script.js

方法B:修正socks-proxy-agent代码

将代理地址改为socks5h://localhost:9999,确保DNS解析走代理:

const url = require('url');
const https = require('https');
const { SocksProxyAgent } = require('socks-proxy-agent');

const proxy = 'socks5h://localhost:9999';
const endpoint = 'https://intranet.mycompany.com/api/todos/';

const opts = url.parse(endpoint);
const agent = new SocksProxyAgent(proxy);
opts.agent = agent;

https.get(opts, function (res) {
    console.log('"response" event!', res.headers);
    res.pipe(process.stdout);
});

2. 使用global-agent强制全局代理(兼容更多Node库)

如果环境变量方式不生效,用global-agent强制所有请求走代理:

  1. 安装依赖:
npm install global-agent
  1. 在脚本开头引入初始化代码:
// ES模块
import 'global-agent/bootstrap';
// CommonJS
// require('global-agent/bootstrap');
  1. 设置环境变量后运行脚本:
export GLOBAL_AGENT_HTTP_PROXY=socks5h://localhost:9999
export GLOBAL_AGENT_HTTPS_PROXY=socks5h://localhost:9999
node your-script.js

验证步骤

先在终端用curl测试代理是否生效:

curl -x socks5h://localhost:9999 https://intranet.mycompany.com/api/todos/

如果能返回接口内容,说明代理配置正确,再运行Node脚本即可。

内容的提问来源于stack exchange,提问作者mistercoffee66

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:51:18