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.
但是问题是大多数第三方模块没有代理设置,我无法修改其代码以添加代理.另外,我的代码可能会在直接连接环境中使用,这意味着我无法在代码中对代理设置进行硬编码.
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
时都设置代理信息.节点不包含用于全局代理设置的机制.
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.
NPM上的 global-tunnel-ng
模块似乎可以解决此问题,但是:
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屋!