Node.js 全局代理设置 [英] Node.js global proxy setting
问题描述
我在代理服务器后面的公司网络中工作.在我的代码中,我可以使用 这个线程.
I was working in a corporate network behind a proxy server. In my code I can set the proxy by using the approach mentioned in this thread.
但问题是大多数第3方模块没有代理设置,我无法修改他们的代码来添加代理.此外,我的代码可能用于直接连接环境,这意味着我无法在代码中硬编码我的代理设置.
But the problem is that most of the 3rd party modules do not have proxy setting and I cannot modify their code to add the proxy. Also, my code might be used in a direct connection environment which means I cannot hard-code my proxy setting in code.
我知道 NPM 有一个全局代理设置
I know NPM has a global setting for proxy which is
npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080
但我没有在 Node.js 中找到任何类似的配置.
But I didn't find any config similar in Node.js.
Node.js 是否支持全局代理设置,无需更改所有代码,轻松开关机?
Does Node.js support global proxy setting so that I don't need to change all codes and switch on and off easily?
推荐答案
不幸的是,似乎每次调用 http.request
时都必须设置代理信息.Node 不包含全局代理设置机制.
Unfortunately, it seems that proxy information must be set on each call to http.request
. Node does not include a mechanism for global proxy settings.
global-tunnel-ng
模块然而,在 NPM 上似乎可以处理这个问题:
The global-tunnel-ng
module on NPM appears to handle this, however:
var globalTunnel = require('global-tunnel-ng');
globalTunnel.initialize({
host: '10.0.0.10',
port: 8080,
proxyAuth: 'userId:password', // optional authentication
sockets: 50 // optional pool size for each http and https
});
在通过调用 initialize
建立全局设置后,http.request
和 request
库 将使用代理信息.
After the global settings are establish with a call to initialize
, both http.request
and the request
library will use the proxy information.
模块也可以使用http_proxy
环境变量:
The module can also use the http_proxy
environment variable:
process.env.http_proxy = 'http://proxy.example.com:3129';
globalTunnel.initialize();
这篇关于Node.js 全局代理设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!