Introduction to global-agent
The global-agent
library is an effective tool that ensures all HTTP/HTTPS requests in your Node.js application go through a specified proxy. Its simplicity and ease of use make it an invaluable library for network management.
Installation
npm install global-agent
APIs Overview
1. Initializing the Proxy Agent
Set the URL to your proxy using the global.GLOBAL_AGENT.HTTP_PROXY
environment variable and initialize the agent.
process.env.GLOBAL_AGENT_HTTP_PROXY = 'http://your-proxy-url:3128';
require('global-agent/bootstrap');
2. Setting Up an HTTPS Proxy
For HTTPS proxy, use the GLOBAL_AGENT_HTTPS_PROXY
variable.
process.env.GLOBAL_AGENT_HTTPS_PROXY = 'https://your-proxy-url:3129';
require('global-agent/bootstrap');
3. Using NO_PROXY for Exclusions
Exclude specific URLs or patterns from going through the proxy by setting the NO_PROXY
environment variable.
process.env.NO_PROXY = 'localhost,127.0.0.1';
require('global-agent/bootstrap');
App Example Using global-agent
Below is an example of a Node.js application that uses global-agent
to manage HTTP/HTTPS requests through a proxy.
// app.js
process.env.GLOBAL_AGENT_HTTP_PROXY = 'http://your-proxy-url:3128';
process.env.GLOBAL_AGENT_HTTPS_PROXY = 'https://your-proxy-url:3129';
process.env.NO_PROXY = 'localhost,127.0.0.1';
require('global-agent/bootstrap');
const https = require('https');
const http = require('http');
// Making an HTTP request
http.get('http://api.example.com/data', (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(data);
});
});
// Making an HTTPS request
https.get('https://api.example.com/data', (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(data);
});
});
With these configurations, all HTTP and HTTPS requests from the application will be routed through the specified proxies, excluding configurations defined in NO_PROXY.
Hash: 554cf6b966ae3c1b54cb4183c5c9a1e8fa917bfb6c4596cae055d68a7637418c