Introduction to global-agent
The global-agent is a powerful tool that simplifies HTTP and HTTPS proxy integrations for Node.js applications. By using a global HTTP/HTTPS agent, global-agent makes it easy to set up proxy connections and ensures your requests are routed efficiently. In this guide, we will cover several useful API examples with code snippets and provide a comprehensive app example utilizing the introduced APIs.
Setting Up global-agent
To get started with global-agent
, you need to install it using npm:
npm install global-agent
Initializing global-agent
Initialize the global-agent in your application by requiring and registering it:
require('global-agent/bootstrap');
Environment Variables
You can configure global-agent using environment variables before bootstrapping:
process.env.GLOBAL_AGENT_HTTP_PROXY = 'http://example.com:8000';
process.env.GLOBAL_AGENT_HTTPS_PROXY = 'https://example.com:8000';
require('global-agent/bootstrap');
Using the Proxy Agent
Once initialized, all your HTTP and HTTPS requests will automatically use the proxy settings. Here’s a simple example with the built-in http
module:
const http = require('http');
http.get('http://example.com', (response) => {
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
response.on('end', () => {
console.log('No more data in response.');
});
});
Setting Custom Headers
You can set custom headers for your proxy requests:
process.env.GLOBAL_AGENT_HTTP_PROXY_HEADERS = JSON.stringify({
'User-Agent': 'MyCustomAgent',
'Proxy-Authorization': 'Basic example'
});
require('global-agent/bootstrap');
Context-Specific Proxy Agent
Sometimes, you may need a context-specific proxy agent instead of a global setup:
const globalAgent = require('global-agent');
const httpProxyAgent = new globalAgent.ProxyAgent('http://example.com:8000');
const http = require('http');
const requestOptions = {
agent: httpProxyAgent,
hostname: 'example.com',
port: 80,
path: '/',
method: 'GET'
};
const req = http.request(requestOptions, (res) => {
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
});
req.end();
Complete Application Example
Here’s a complete example of an application using global-agent to perform HTTP operations through a proxy:
// index.js
process.env.GLOBAL_AGENT_HTTP_PROXY = 'http://example-proxy.com:8000';
process.env.GLOBAL_AGENT_HTTPS_PROXY = 'https://example-proxy.com:8000';
require('global-agent/bootstrap');
const http = require('http');
const https = require('https');
function fetchUrl(url) {
return new Promise((resolve, reject) => {
const client = url.startsWith('https') ? https : http;
client.get(url, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
resolve(data);
});
}).on('error', (err) => {
reject(err);
});
});
}
async function main() {
try {
const data = await fetchUrl('http://example.com');
console.log(data);
} catch (error) {
console.error('Error fetching URL:', error);
}
}
main();
With the above example, you can easily perform HTTP requests with your application routing through a proxy server using global-agent.
Hash: 554cf6b966ae3c1b54cb4183c5c9a1e8fa917bfb6c4596cae055d68a7637418c