Проксі з Node.js: покроковий посібник
У цьому посібнику я розповім про основи роботи з проксі Node.js. We’ll go over the different types of proxies, how they work, and practical ways to use them with popular Node.js libraries.
By the end, you’ll have a clear understanding of how to set up proxies in your Node.js projects and why they can be useful. Whether you’re just starting out or looking to optimize your setup, this guide will make proxies easy to grasp.
Що таке проксі?
Проксі-сервер — це проміжний сервер, який отримує запити від клієнта та пересилає їх до цільового сервера. У відповідь він повертає її клієнту. Така схема дає змогу проксі-серверу приховувати IP-адресу клієнта та забезпечувати анонімність, безпеку або фільтрацію вмісту.
Існує кілька типів проксі, але в цій статті ми зосередимося на популярних прямі проксі, які здебільшого використовують для вебскрапінг:
- Datacenter ProxiesЦе проксі, розміщені в дата-центрах, які пропонують швидкі, економічно вигідні рішення для вебскрапінгу великих обсягів даних, але їх легше виявити.
- ISP Proxies: використовують IP-адреси, надані інтернет-провайдерами Вони поєднують швидкість і легітимність, що робить їх складнішими для блокування, ніж дата-центрові проксі.
- Mobile Proxies: використовують IP-адреси, призначені мобільним пристроям, забезпечуючи високу анонімність і ротацію, що робить їх чудовими для обходу суворих антиботових заходів.
- Residential ProxiesЦе прив'язані до реальних пристроїв користувачів і забезпечують високу анонімність, що робить їх ідеальними для вебскрапінгу даних із вебсайтів із суворим геоблокуванням та фільтрами безпеки.
Ми зосередимося на цих прямих проксі, оскільки вони є ключовими для вебскрапінгу та обходу обмежень.
Why Use Proxies with Node.js?
Proxies can offer several advantages for Node.js applications, such as:
- Bypassing Geo-Restrictions: Ви можете отримати доступ до контенту або API, географічно обмежених.
- Балансування навантаження та розподіл трафіку: Зворотні проксі допомагають розподіляти трафік між різними екземплярами серверів, підвищуючи надійність і продуктивність вашого застосунку.
- Caching: Проксі можуть кешувати дані, щоб зменшити кількість запитів до сервера-джерела для отримання того самого контенту.
- Enhanced Security: Проксі можуть виконувати роль захисного шару, блокуючи шкідливі запити або атаки ще до того, як вони досягнуть вашого сервера.
Setting Up Proxies in Node.js
To implement proxies in Node.js, you can use libraries like http-proxy and node-fetch. Let’s start by using http-proxy, a popular proxy library in the Node.js ecosystem.
Крок 1: Встановіть http-proxy
Почніть із встановлення пакета http-proxy у каталозі вашого проєкту.
npm install http-proxy
Крок 2: Базове налаштування проксі за допомогою http-proxy
Після встановлення пакета ви можете створити простий проксі-сервер. Ось приклад прямого проксі:
const http = require('http');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
const server = http.createServer((req, res) => {
proxy.web(req, res, { target: 'http://example.com' }, (err) => {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Щось пішло не так.');
});
});
server.listen(3000, () => {
console.log('Proxy server is running on http://localhost:3000');
});
In this example, the proxy forwards all incoming requests to http://example.com. If you access http://localhost:3000, the request will be forwarded to the target site.
Крок 3: Обробка помилок і подій
Проксі часто стикаються з помилками, як-от проблеми з підключенням або некоректні запити. Їх можна обробляти, відстежуючи подію помилки.
proxy.on('error', (err, req, res) => {
console.error('Помилка проксі:', err);
res.writeHead(502, { 'Content-Type': 'text/plain' });
res.end('Неправильний шлюз.');
});
Це гарантує, що якщо з проксі щось піде не так, клієнт отримає інформативну відповідь.
Step 4: Reverse Proxy with Node.js
Щоб налаштувати зворотний проксі (той, що спрямовує трафік до кількох серверів), можна змінити код так:
const servers = ['http://localhost:3001', 'http://localhost:3002'];
const server = http.createServer((req, res) => {
const target = servers[Math.floor(Math.random() * сервери.length)];
proxy.web(req, res, { target });
});
server.listen(3000, () => {
console.log('Reverse proxy running on http://localhost:3000');
});
Використання проксі з node-fetch
The node-fetch library is commonly used for making HTTP requests in Node.js applications. You can easily add proxy support using http-proxy-agent for HTTP proxies or https-proxy-agent for HTTPS proxies.
Крок 1: Встановіть node-fetch і Proxy Agent
npm install node-fetch http-proxy-agent
Крок 2: Реалізуйте проксі за допомогою node-fetch
Ось як налаштувати node-fetch з проксі:
const fetch = require('node-fetch');
const HttpProxyAgent = require('http-proxy-agent');
const proxyAgent = new HttpProxyAgent('http://your-proxy-server:8080');
fetch('http://example.com', { agent: proxyAgent })
.then(res => res.text())
.then(body => console.log(body)) .catch(err => console.error('Помилка Fetch:', err));
In this example, all requests made using node-fetch are routed through the specified proxy server (http://your-proxy-server:8080).
Proxies in Enterprise-Level Node.js Applications
Proxies are not just useful for small projects. Large-scale Node.js applications, especially microservices-based architectures, frequently use reverse proxies for routing and load balancing. Nginx and HAProxy are common tools used as reverse proxies for Node.js apps.
У мікросервісах зворотні проксі можуть:
- Manage Traffic: Переадресовуйте вхідні запити до різних мікросервісів залежно від маршрутів.
- Improve Security: Приховуйте справжні IP-адреси сервера та впроваджуйте заходи безпеки до того, як трафік потрапить до внутрішньої мережі.
- Enable Scalability: Розподіляти запити між кількома екземплярами, щоб забезпечити високу доступність ваших сервісів.
Proxy Authentication
In some cases, proxy servers require authentication. You can add authentication headers to your proxy requests using Node.js.
const options = {
target: 'http://example.com',
headers: {
'Proxy-Authorization': 'Basic ' + Buffer.from('username:password').toString('base64'),
},
};
proxy.web(req, res, options);
Це надсилає заголовок авторизації, що містить облікові дані, закодовані в base64 (username:password), і дає змогу отримувати доступ до проксі, які вимагають автентифікації.
Best Proxy Servers for Node.js
- Bright Data
Bright Data offers top-tier proxy services, including datacenter, residential, and mobile proxies, ideal for Node.js applications needing high scalability, IP rotation, and advanced CAPTCHA solving. Its vast network ensures reliability and compliance. - ScraperAPI
Known for its ease of integration with Node.js, ScraperAPI provides automatic IP rotation, CAPTCHA solving, and anti-bot protection, making it perfect for large-scale web scraping. - Oxylabs
Oxylabs offers robust proxy services, including datacenter and residential proxies. It’s highly secure and works well with Node.js for scraping and API-driven projects. - NetNut
NetNut offers residential proxies that are reliable and fast, making them an excellent choice for Node.js users who need consistent performance and minimal downtime for scraping or API tasks. - Smartproxy
Smartproxy provides affordable residential and datacenter proxies, offering a wide range of IPs for web scraping, with a straightforward setup process for Node.js users.
Conclusion
Proxies are essential tools when building with Node.js. Whether you need to bypass geo-restrictions, balance traffic, or add security layers to your app, proxies can make a big difference. With libraries like http-proxy and node-fetch, setting up proxies is straightforward. They give you the flexibility to add forward or reverse proxies depending on what your project needs.
No matter if you’re building a small Node.js API or working on a large microservice system, proxies will help you improve performance, strengthen security, and manage traffic more efficiently. When you understand how to use them effectively, your applications become more reliable and scalable.
Є запитання? Пишіть у коментарях!

