https.globalAgent JavaScript and Node.js code examples
Best JavaScript code snippets using obalAgent(Showing top 10 results out of 315)describe(“#NodeHttpStack”, function () {
it(“should allow to pass options to Node’s requests”, async function () {
const customAgent = new ();
const stack = (new tpStack({
agent: customAgent}));
const req = eateRequest(“GET”, “);
await ();
expect(tUnderlyingObject())(customAgent);
expect(tUnderlyingObject())(obalAgent);});});
(‘/_stats’, (req, res) => {
({: {
sockets: socketStats(ckets),
freeSockets: socketStats(eeSockets), }, : {
freeSockets: socketStats(eeSockets), }, });});
constructor(options){
super();
tpsAgent = obalAgent;
tpAgent = obalAgent;
(options);}
const setupHTTPClient = () => {
if (eCertFile) {
if (Config. certFile! == undefined) {
= [adFileSync(Config. certFile)];
(‘Loaded cert file:’, Config. certFile);}}
epAlive = epAlive;
epAlive = epAlive;}
rEach(userDefinedCAStores, store => {
(adFileSync(store));});
constructor(){
super(guments);
=;
obalAgent = obalAgent;
this. enforceProtocol = ‘:’;}
if (code === ‘200’) {
if (use_secure === ‘disable’) {
xSockets = 1000000;
eateServer(app)({port: usecsebaseport, agent: false}, function () {
(‘mobius server (‘ + dress() + ‘) running at ‘ + usecsebaseport + ‘ port’);
ca: adFileSync(”)};
eateServer(options, app)({port: usecsebaseport, agent: false}, function () {
= [];
epAlive = false;
eCertFile = false;
expect()(0);
setupHTTPClient();
expect()(1);});
expect()(0);});
expect(epAlive);
expect(epAlive);});
epAlive = true;
(‘mobius server (‘ + dress() + ‘) running at ‘ + usecsebaseport + ‘ port’);
global-agent – npm
Global HTTP/HTTPS proxy configurable using environment variables.
Usage
Setup proxy using global-agent/bootstrap
Setup proxy using bootstrap routine
Runtime configuration
Exclude URLs
Enable logging
API
createGlobalProxyAgent
Environment variables
OBAL_AGENT
Supported libraries
FAQ
What is the reason global-agent overrides explicitly configured HTTP(S) agent?
What is the reason global-agent/bootstrap does not use HTTP_PROXY?
What is the difference from global-tunnel and tunnel?
To configure HTTP proxy:
Import global-agent/bootstrap. Export HTTP proxy address as GLOBAL_AGENT_HTTP_PROXY environment variable.
Code:
import ‘global-agent/bootstrap’;
// or:
// import {bootstrap} from ‘global-agent’;
// bootstrap();
Bash:
$ export GLOBAL_AGENT_HTTP_PROXY=
Alternatively, you can preload module using –require, -r configuration, e. g.
$ export GLOBAL_AGENT_HTTP_PROXY=$ node -r ‘global-agent/bootstrap’
Instead of importing a self-initialising script with side-effects as demonstrated in the setup proxy using global-agent/bootstrap documentation, you can import bootstrap routine and explicitly evaluate the bootstrap logic, e. g.
import {
bootstrap} from ‘global-agent’;
bootstrap();
This is useful if you need to conditionally bootstrap global-agent, e. g.
import globalTunnel from ‘global-tunnel-ng’;
const MAJOR_NODEJS_VERSION = parseInt((1)(‘. ‘)[0], 10);
if (MAJOR_NODEJS_VERSION >= 10) {
// `global-agent` works with v10 and above.
bootstrap();} else {
// `global-tunnel-ng` works only with v10 and below.
itialize();}
Setup proxy using createGlobalProxyAgent
If you do not want to use OBAL_AGENT variable, then you can use createGlobalProxyAgent to instantiate a controlled instance of global-agent, e. g.
createGlobalProxyAgent} from ‘global-agent’;
const globalProxyAgent = createGlobalProxyAgent();
Unlike bootstrap routine, createGlobalProxyAgent factory does not create OBAL_AGENT variable and does not guard against multiple initializations of global-agent. The result object of createGlobalProxyAgent is equivalent to OBAL_AGENT.
global-agent/bootstrap script copies value to TP_PROXY and continues to use the latter variable.
You can override the TP_PROXY value at runtime to change proxy behaviour, e. g.
(”);
TP_PROXY = ”;
The first HTTP request is going to use proxy and the secord request is going to use All global-agent configuration is available under OBAL_AGENT namespace.
The GLOBAL_AGENT_NO_PROXY environment variable specifies a pattern of URLs that should be excluded from proxying. GLOBAL_AGENT_NO_PROXY value is a comma-separated list of domain names. Asterisks can be used as wildcards, e. g.
export GLOBAL_AGENT_NO_PROXY=’*, ‘
says to contact all machines with the ” TLD and ” domains directly.
Separate proxy for HTTPS
The environment variable GLOBAL_AGENT_HTTPS_PROXY can be set to specify a separate proxy for HTTPS requests. When this variable is not set GLOBAL_AGENT_HTTP_PROXY is used for both HTTP and HTTPS requests.
global-agent is using roarr logger to log HTTP requests and response (HTTP status code and headers), e. g.
{“context”:{“program”:”global-agent”, “namespace”:”Agent”, “logLevel”:10, “destination”:”, “proxy”:”}, “message”:”proxying request”, “sequence”:1, “time”:1556269669663, “version”:”1. 0. 0″}
{“context”:{“program”:”global-agent”, “namespace”:”Agent”, “logLevel”:10, “headers”:{“content-type”:”text/plain”, “content-length”:”2″, “date”:”Fri, 26 Apr 2019 12:07:50 GMT”, “connection”:”close”}, “requestId”:6, “statusCode”:200}, “message”:”proxying response”, “sequence”:2, “time”:1557133856955, “version”:”1. 0″}
Export ROARR_LOG=true environment variable to enable log printing to stdout.
Use roarr-cli program to pretty-print the logs.
/**
* @property environmentVariableNamespace Defines namespace of `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` environment variables. (Default: `GLOBAL_AGENT_`)
* @property forceGlobalAgent Forces to use `global-agent` HTTP(S) agent even when request was explicitly constructed with another agent. (Default: `true`)
* @property socketConnectionTimeout Destroys socket if connection is not established within the timeout. (Default: `60000`)
*/
type ProxyAgentConfigurationInputType = {|
+environmentVariableNamespace? : string,
+forceGlobalAgent? : boolean,
+socketConnectionTimeout? : number,
|};
(configurationInput: ProxyAgentConfigurationInputType) => ProxyAgentConfigurationType;
Name
Description
Default
GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE
Defines namespace of HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables.
GLOBAL_AGENT_
GLOBAL_AGENT_FORCE_GLOBAL_AGENT
Forces to use global-agent HTTP(S) agent even when request was explicitly constructed with another agent.
true
GLOBAL_AGENT_SOCKET_CONNECTION_TIMEOUT
Destroys socket if connection is not established within the timeout.
60000
${NAMESPACE}_HTTP_PROXY
Sets the initial proxy controller HTTP_PROXY value.
N/A
${NAMESPACE}_HTTPS_PROXY
Sets the initial proxy controller HTTPS_PROXY value.
${NAMESPACE}_NO_PROXY
Sets the initial proxy controller NO_PROXY value.
OBAL_AGENT is initialized by bootstrap routine.
OBAL_AGENT has the following properties:
Configurable
HTTP_PROXY
Yes
Sets HTTP proxy to use.
HTTPS_PROXY
Sets a distinct proxy to use for HTTPS requests.
NO_PROXY
Specifies a pattern of URLs that should be excluded from proxying. See Exclude URLs.
global-agent works with all libraries that internally use quest.
global-agent has been tested to work with:
got
axios
request
By default, global-agent overrides agent property of any HTTP request, even if agent property was explicitly set when constructing a HTTP request. This behaviour allows to intercept requests of libraries that use a custom instance of an agent per default (e. g. Stripe SDK uses an (s). globalAgent instance pre-configured with keepAlive: true).
This behaviour can be disabled with GLOBAL_AGENT_FORCE_GLOBAL_AGENT=false environment variable. When disabled, then global-agent will only set agent property when it is not already defined or if agent is an instance of (s). globalAgent.
Some libraries (e. request) change their behaviour when HTTP_PROXY environment variable is present. Using a namespaced environment variable prevents conflicting library behaviour.
You can override this behaviour by configuring GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE variable, e. g.
$ export GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE=
Now script initialized using global-agent/bootstrap will use HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables.
global-tunnel (including global-tunnel-ng and tunnel) are designed to support legacy versions. They use various workarounds and rely on monkey-patching quest,, quest and methods.
In contrast, global-agent supports v10 and above, and does not implements workarounds for the older versions.
HTTP | Node.js v17.0.1 Documentation
HTTP#
Source Code: lib/
To use the HTTP server and client one must require(”).
The HTTP interfaces in are designed to support many features
of the protocol which have been traditionally difficult to use.
In particular, large, possibly chunk-encoded, messages. The interface is
careful to never buffer entire requests or responses, so the
user is able to stream data.
HTTP message headers are represented by an object like this:
{ ‘content-length’: ‘123’,
‘content-type’: ‘text/plain’,
‘connection’: ‘keep-alive’,
‘host’: ”,
‘accept’: ‘*/*’}
Keys are lowercased. Values are not modified.
In order to support the full spectrum of possible HTTP applications, the
HTTP API is very low-level. It deals with stream handling and message
parsing only. It parses a message into headers and body but it does not
parse the actual headers or the body.
See message. headers for details on how duplicate headers are handled.
The raw headers as they were received are retained in the rawHeaders
property, which is an array of [key, value, key2, value2,… ]. For
example, the previous message header object might have a rawHeaders
list like the following:
[ ‘ConTent-Length’, ‘123456’,
‘content-LENGTH’, ‘123’,
‘content-type’, ‘text/plain’,
‘CONNECTION’, ‘keep-alive’,
‘Host’, ”,
‘accepT’, ‘*/*’]
Class:
Added in: v0. 3. 4
An Agent is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on the
keepAlive option.
Pooled connections have TCP Keep-Alive enabled for them, but servers may
still close idle connections, in which case they will be removed from the
pool and a new connection will be made when a new HTTP request is made for
that host and port. Servers may also refuse to allow multiple requests
over the same connection, in which case the connection will have to be
remade for every request and cannot be pooled. The Agent will still make
the requests to that server, but each one will occur over a new connection.
When a connection is closed by the client or the server, it is removed
from the pool. Any unused sockets in the pool will be unrefed so as not
to keep the process running when there are no outstanding requests.
(see ()).
It is good practice, to destroy() an Agent instance when it is no
longer in use, because unused sockets consume OS resources.
Sockets are removed from an agent when the socket emits either
a ‘close’ event or an ‘agentRemove’ event. When intending to keep one
HTTP request open for a long time without keeping it in the agent, something
like the following may be done:
(options, (res) => {
// Do stuff})(‘socket’, (socket) => {
(‘agentRemove’);});
An agent may also be used for an individual request. By providing
{agent: false} as an option to the () or quest()
functions, a one-time use Agent with default options will be used
for the client connection.
agent:false:
({
hostname: ‘localhost’,
port: 80,
path: ‘/’,
agent: false // Create a new agent just for this one request}, (res) => {
// Do stuff with response});
new Agent([options])#
options