Node.js uygulamaları geliştirirken, veri çekme, otomasyon veya API'lerle çalışma amacıyla sıklıkla proxy sunucularının kullanılması gerekmektedir. Bu, coğrafi kısıtlamaları aşmayı, yükü dağıtmayı ve IP engellemelerinden kaçınmayı sağlar. Bu kılavuzda, Node.js'te proxy ayarlamanın tüm yollarını inceleyeceğiz — temel ayarlamalardan döngü ve hata işleme gibi ileri tekniklere kadar.
Node.js'te Proxy ile Çalışmanın Temel Kavramları
Node.js'te proxy sunucusu, uygulamanız ile hedef sunucu arasında bir aracı olarak çalışır. Proxy üzerinden bir HTTP isteği gönderdiğinizde, uygulamanız önce proxy sunucusuna bağlanır ve bu sunucu isteği son adrese yönlendirir. Bu, sunucunuzun gerçek IP adresini gizlemeyi ve proxy'nin IP adresini kullanmayı sağlar.
Node.js'te, kullanılan HTTP istek kütüphanesine bağlı olarak proxy ile çalışmanın birkaç temel yolu vardır. En popüler seçenekler:
- Yerleşik http/https Modülleri — ek bağımlılık olmadan temel işlevsellik
- Axios — kullanışlı bir API ve promise desteği ile popüler bir kütüphane
- Got — TypeScript desteği ile modern bir alternatif
- node-fetch — Node.js için Fetch API uygulaması
- request — eski ama hala kullanılan bir kütüphane (yeni projeler için önerilmez)
Proxy sunucuları çeşitli protokolleri destekler. Node.js ile en sık kullanılanlar:
| Protokol | Açıklama | Kullanım |
|---|---|---|
| HTTP | Şifrelenmemiş bağlantılar için temel protokol | Veri çekme, SSL olmadan API ile çalışma |
| HTTPS | SSL/TLS şifrelemesi destekleyen proxy | Güvenli bağlantılar, korumalı API ile çalışma |
| SOCKS5 | Herhangi bir trafik türü için evrensel protokol | WebSocket, UDP, karmaşık senaryolar |
Veri çekme ve otomasyon görevleri için geliştiriciler genellikle konut proxy'leri kullanır, çünkü bunlar gerçek ev kullanıcılarının IP adreslerine sahiptir ve hedef siteler tarafından daha az engellenir.
Yerleşik http/https Modülü ile Proxy Ayarlama
Node.js, HTTP istekleri için http ve https adında yerleşik modüller sunar. Proxy bağlantısı için http-proxy-agent veya https-proxy-agent kütüphanesini kullanabilirsiniz.
Öncelikle gerekli paketleri yükleyin:
npm install http-proxy-agent https-proxy-agent
Yerleşik modül ile HTTP proxy kullanımı örneği:
const http = require('http');
const { HttpProxyAgent } = require('http-proxy-agent');
// Proxy ayarları
const proxyUrl = 'http://username:password@proxy-server.com:8080';
const agent = new HttpProxyAgent(proxyUrl);
// İstek seçenekleri
const options = {
hostname: 'api.example.com',
path: '/endpoint',
method: 'GET',
agent: agent,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
};
// İsteği gerçekleştirme
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Yanıt:', data);
});
});
req.on('error', (error) => {
console.error('İstek başarısız oldu:', error.message);
});
req.end();
HTTPS bağlantıları için https-proxy-agent kullanın:
const https = require('https');
const { HttpsProxyAgent } = require('https-proxy-agent');
const proxyUrl = 'http://username:password@proxy-server.com:8080';
const agent = new HttpsProxyAgent(proxyUrl);
const options = {
hostname: 'api.example.com',
path: '/secure-endpoint',
method: 'GET',
agent: agent
};
https.get(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Güvenli yanıt:', data);
});
}).on('error', (error) => {
console.error('HTTPS isteği başarısız oldu:', error.message);
});
Bu yaklaşım, istekler üzerinde maksimum kontrol sağlar, ancak promise'leri ve hataları işlemek için daha fazla kod gerektirir. Çoğu görev için özel kütüphaneleri kullanmak daha kullanışlıdır.
Axios Kütüphanesinde Proxy ile Çalışma
Axios, Node.js'te HTTP istekleri için en popüler kütüphanelerden biridir. Proxy ayarlamak için kullanışlı bir API sunar ve otomatik olarak promise'leri işler.
Axios'u yüklemek için:
npm install axios
Axios'ta proxy ayarlamak için temel yapı şu şekildedir:
const axios = require('axios');
// Yöntem 1: İstek yapılandırmasında proxy ayarlama
axios.get('https://api.example.com/data', {
proxy: {
protocol: 'http',
host: 'proxy-server.com',
port: 8080,
auth: {
username: 'your-username',
password: 'your-password'
}
}
})
.then(response => {
console.log('Veri:', response.data);
})
.catch(error => {
console.error('Hata:', error.message);
});
Aynı proxy ayarlarını tekrar kullanmak için, önceden ayarlanmış bir yapılandırma ile bir Axios örneği oluşturmak kullanışlıdır:
const axios = require('axios');
// Proxy ayarları ile bir örnek oluşturma
const axiosWithProxy = axios.create({
proxy: {
protocol: 'http',
host: 'proxy-server.com',
port: 8080,
auth: {
username: 'your-username',
password: 'your-password'
}
},
timeout: 10000,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
// Örneği kullanma
async function fetchData() {
try {
const response = await axiosWithProxy.get('https://api.example.com/data');
console.log('Yanıt:', response.data);
return response.data;
} catch (error) {
console.error('İstek başarısız oldu:', error.message);
throw error;
}
}
fetchData();
HTTPS proxy ile CONNECT yöntemi üzerinden çalışmak için ek ajanlar kullanabilirsiniz:
const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');
const proxyUrl = 'http://username:password@proxy-server.com:8080';
const httpsAgent = new HttpsProxyAgent(proxyUrl);
const axiosInstance = axios.create({
httpsAgent: httpsAgent,
timeout: 15000
});
// Kullanım
axiosInstance.get('https://api.example.com/secure-data')
.then(response => console.log(response.data))
.catch(error => console.error(error.message));
Axios, yönlendirmeleri otomatik olarak işler ve hata işleme ve günlüğe kaydetme için interceptors destekler, bu da onu proxy'leri aktif bir şekilde kullanan projeler için mükemmel bir seçim haline getirir.
Got ve node-fetch'te Proxy Ayarlama
Got, mükemmel TypeScript desteği ve gelişmiş hata işleme yetenekleri ile modern bir Axios alternatifi. Node-fetch, Node.js için standart Fetch API'yi uygular.
Got ile Proxy ile Çalışma
Got ve gerekli ajanları yüklemek:
npm install got https-proxy-agent
Got'ta proxy ayarlama örneği:
const got = require('got');
const { HttpsProxyAgent } = require('https-proxy-agent');
const proxyUrl = 'http://username:password@proxy-server.com:8080';
const agent = {
https: new HttpsProxyAgent(proxyUrl)
};
// Proxy ile Got örneği oluşturma
const gotWithProxy = got.extend({
agent: agent,
timeout: {
request: 10000
},
retry: {
limit: 3,
methods: ['GET', 'POST']
}
});
// Kullanım
async function fetchWithGot() {
try {
const response = await gotWithProxy('https://api.example.com/data');
console.log('Yanıt:', JSON.parse(response.body));
} catch (error) {
console.error('Got isteği başarısız oldu:', error.message);
}
}
fetchWithGot();
node-fetch ile Proxy ile Çalışma
Node-fetch, proxy ile çalışmak için açık bir ajan ayarı gerektirir:
npm install node-fetch https-proxy-agent
const fetch = require('node-fetch');
const { HttpsProxyAgent } = require('https-proxy-agent');
const proxyUrl = 'http://username:password@proxy-server.com:8080';
const agent = new HttpsProxyAgent(proxyUrl);
async function fetchWithProxy() {
try {
const response = await fetch('https://api.example.com/data', {
agent: agent,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
}
});
if (!response.ok) {
throw new Error(`HTTP hatası! durum: ${response.status}`);
}
const data = await response.json();
console.log('Veri:', data);
return data;
} catch (error) {
console.error('Fetch başarısız oldu:', error.message);
throw error;
}
}
fetchWithProxy();
Got, kutudan daha zengin bir işlevsellik sunar (otomatik tekrarlar, zaman aşımı, hata işleme), node-fetch ise standart Fetch API'ye daha yakındır ve tarayıcı JavaScript'i ile tanışık olan geliştiriciler için uygundur.
socks-proxy-agent ile SOCKS5 Proxy Bağlantısı
SOCKS5, HTTP/HTTPS'ten daha düşük bir seviyede çalışan evrensel bir proxy protokolüdür. UDP ve WebSocket bağlantıları da dahil olmak üzere her türlü trafiği destekler. Node.js'te SOCKS5 ile çalışmak için socks-proxy-agent kütüphanesi kullanılır.
Gerekli paketleri yüklemek:
npm install socks-proxy-agent
Çeşitli kütüphanelerle SOCKS5 proxy kullanımı örneği:
const { SocksProxyAgent } = require('socks-proxy-agent');
const https = require('https');
// Yetkilendirme ile SOCKS5 proxy ayarlama
const proxyUrl = 'socks5://username:password@proxy-server.com:1080';
const agent = new SocksProxyAgent(proxyUrl);
const options = {
hostname: 'api.example.com',
path: '/endpoint',
method: 'GET',
agent: agent
};
https.get(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('SOCKS5 yanıtı:', data);
});
}).on('error', (error) => {
console.error('SOCKS5 isteği başarısız oldu:', error.message);
});
Axios ile SOCKS5 kullanımı:
const axios = require('axios');
const { SocksProxyAgent } = require('socks-proxy-agent');
const proxyUrl = 'socks5://username:password@proxy-server.com:1080';
const httpsAgent = new SocksProxyAgent(proxyUrl);
const httpAgent = new SocksProxyAgent(proxyUrl);
const axiosWithSocks = axios.create({
httpAgent: httpAgent,
httpsAgent: httpsAgent,
timeout: 15000
});
async function fetchViaSocks5() {
try {
const response = await axiosWithSocks.get('https://api.example.com/data');
console.log('Veri SOCKS5 üzerinden:', response.data);
return response.data;
} catch (error) {
console.error('SOCKS5 isteği hatası:', error.message);
throw error;
}
}
fetchViaSocks5();
SOCKS5 proxy, standart olmayan protokollerle çalışması gereken veya maksimum esneklik gerektiren görevler için özellikle faydalıdır. Birçok sağlayıcı, mobil API'lerle çalışmak için mobil trafiği taklit etmeyi sağlayan mobil proxy'ler sunmaktadır.
Yük Dağıtımı için Proxy Döngüsü Uygulaması
Büyük veri setlerini çekme veya bir IP'den gelen istek sayısına sınırlamalar getiren API'lerle çalışırken, proxy döngüsü kullanmak gereklidir. Bu, istekleri birden fazla proxy sunucusu arasında dağıtmayı ve engellemelerden kaçınmayı sağlar.
Basit bir proxy döngüsü uygulama örneği:
const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');
class ProxyRotator {
constructor(proxyList) {
this.proxyList = proxyList;
this.currentIndex = 0;
}
// Döngüsel olarak bir sonraki proxy'yi al
getNextProxy() {
const proxy = this.proxyList[this.currentIndex];
this.currentIndex = (this.currentIndex + 1) % this.proxyList.length;
return proxy;
}
// Rastgele bir proxy al
getRandomProxy() {
const randomIndex = Math.floor(Math.random() * this.proxyList.length);
return this.proxyList[randomIndex];
}
// Mevcut proxy ile bir Axios örneği oluştur
createAxiosInstance(useRandom = false) {
const proxyUrl = useRandom ? this.getRandomProxy() : this.getNextProxy();
const agent = new HttpsProxyAgent(proxyUrl);
return axios.create({
httpsAgent: agent,
timeout: 10000,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
}
}
// Proxy listesi
const proxyList = [
'http://user1:pass1@proxy1.example.com:8080',
'http://user2:pass2@proxy2.example.com:8080',
'http://user3:pass3@proxy3.example.com:8080',
'http://user4:pass4@proxy4.example.com:8080'
];
const rotator = new ProxyRotator(proxyList);
// Döngü kullanarak istek
async function fetchWithRotation(url) {
const axiosInstance = rotator.createAxiosInstance();
try {
const response = await axiosInstance.get(url);
console.log('Proxy ile başarılı');
return response.data;
} catch (error) {
console.error('İstek başarısız oldu:', error.message);
throw error;
}
}
// Örnek toplu veri çekme ile döngü
async function massiveParsing(urls) {
const results = [];
for (const url of urls) {
try {
const data = await fetchWithRotation(url);
results.push({ url, success: true, data });
// İstekler arasında gecikme
await new Promise(resolve => setTimeout(resolve, 1000));
} catch (error) {
results.push({ url, success: false, error: error.message });
}
}
return results;
}
// Veri çekmeyi başlatma
const urlsToParse = [
'https://api.example.com/data/1',
'https://api.example.com/data/2',
'https://api.example.com/data/3',
'https://api.example.com/data/4',
'https://api.example.com/data/5'
];
massiveParsing(urlsToParse)
.then(results => console.log('Veri çekme sonuçları:', results))
.catch(error => console.error('Veri çekme hatası:', error));
Çalışmayan proxy'leri izleyen ve otomatik olarak hariç tutan daha gelişmiş bir örnek:
class AdvancedProxyRotator {
constructor(proxyList, maxFailures = 3) {
this.proxyList = proxyList.map(url => ({
url,
failures: 0,
active: true,
lastUsed: null
}));
this.maxFailures = maxFailures;
this.currentIndex = 0;
}
// Aktif bir proxy al
getActiveProxy() {
const activeProxies = this.proxyList.filter(p => p.active);
if (activeProxies.length === 0) {
throw new Error('Aktif proxy mevcut değil');
}
// En uzun süredir kullanılmayan proxy'yi bul
const proxy = activeProxies.reduce((oldest, current) => {
if (!oldest.lastUsed) return oldest;
if (!current.lastUsed) return current;
return current.lastUsed < oldest.lastUsed ? current : oldest;
});
proxy.lastUsed = Date.now();
return proxy;
}
// Proxy'yi başarılı olarak işaretle
markSuccess(proxyUrl) {
const proxy = this.proxyList.find(p => p.url === proxyUrl);
if (proxy) {
proxy.failures = 0;
}
}
// Proxy'yi başarısız olarak işaretle
markFailure(proxyUrl) {
const proxy = this.proxyList.find(p => p.url === proxyUrl);
if (proxy) {
proxy.failures++;
if (proxy.failures >= this.maxFailures) {
proxy.active = false;
console.warn(`Proxy ${proxyUrl} ${proxy.failures} başarısızlıktan sonra devre dışı bırakıldı`);
}
}
}
// Döngü ile bir Axios örneği oluştur
async createAxiosInstance() {
const proxy = this.getActiveProxy();
const agent = new HttpsProxyAgent(proxy.url);
return {
instance: axios.create({
httpsAgent: agent,
timeout: 10000
}),
proxyUrl: proxy.url
};
}
// Proxy istatistiklerini al
getStats() {
return {
total: this.proxyList.length,
active: this.proxyList.filter(p => p.active).length,
inactive: this.proxyList.filter(p => !p.active).length,
proxies: this.proxyList.map(p => ({
url: p.url.replace(/\/\/.*@/, '//***@'), // Kimlik bilgilerini gizle
active: p.active,
failures: p.failures
}))
};
}
}
// Gelişmiş döndürücü kullanımı
const advancedRotator = new AdvancedProxyRotator(proxyList);
async function fetchWithAdvancedRotation(url) {
const { instance, proxyUrl } = await advancedRotator.createAxiosInstance();
try {
const response = await instance.get(url);
advancedRotator.markSuccess(proxyUrl);
return response.data;
} catch (error) {
advancedRotator.markFailure(proxyUrl);
throw error;
}
}
// İstatistikleri periyodik olarak yazdırma
setInterval(() => {
console.log('Proxy istatistikleri:', advancedRotator.getStats());
}, 30000);
Bu sistem, çalışmayan proxy'leri döngüden otomatik olarak hariç tutar ve aktif sunucular arasında yükü eşit olarak dağıtır. Bu, büyük veri setleri ile çalışırken kritik öneme sahiptir.
Hata İşleme ve Otomatik Proxy Geçişi
Proxy ile çalışırken zaman aşımı, bağlantı reddi, hedef sunucu tarafından engellemeler gibi hatalar kaçınılmazdır. Hataların doğru bir şekilde işlenmesi ve başka bir proxy'ye otomatik geçiş, uygulamanın güvenilirliğini artırır.
Otomatik tekrarlar ve proxy geçişi ile bir sistemin uygulanmasına örnek:
const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');
class ResilientProxyClient {
constructor(proxyList, maxRetries = 3) {
this.proxyList = proxyList;
this.maxRetries = maxRetries;
this.currentProxyIndex = 0;
}
// Bir sonraki proxy'yi al
getNextProxy() {
const proxy = this.proxyList[this.currentProxyIndex];
this.currentProxyIndex = (this.currentProxyIndex + 1) % this.proxyList.length;
return proxy;
}
// Hata türünü belirle
isRetryableError(error) {
// Tekrar isteği yapılması gereken hatalar
const retryableCodes = ['ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED'];
const retryableStatuses = [408, 429, 500, 502, 503, 504];
if (error.code && retryableCodes.includes(error.code)) {
return true;
}
if (error.response && retryableStatuses.includes(error.response.status)) {
return true;
}
return false;
}
// Otomatik tekrarlarla isteği gerçekleştirin
async request(url, options = {}, attempt = 1) {
const proxyUrl = this.getNextProxy();
const agent = new HttpsProxyAgent(proxyUrl);
const config = {
...options,
httpsAgent: agent,
timeout: 10000,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
...options.headers
}
};
try {
console.log(`Deneme ${attempt}/${this.maxRetries} proxy ile: ${proxyUrl.replace(/\/\/.*@/, '//***@')}`);
const response = await axios.get(url, config);
console.log(`Deneme ${attempt} başarılı`);
return response.data;
} catch (error) {
console.error(`Deneme ${attempt} başarısız oldu: ${error.message}`);
// Maksimum tekrar sayısına ulaşıldıysa
if (attempt >= this.maxRetries) {
console.error(`Maksimum tekrar sayısına (${this.maxRetries}) ulaşıldı: ${url}`);
throw error;
}
// Hata tekrar edilemezse
if (!this.isRetryableError(error)) {
console.error(`Tekrar edilemez hata: ${error.message}`);
throw error;
}
// Tekrar öncesi üssel gecikme
const delay = Math.min(1000 * Math.pow(2, attempt - 1), 10000);
console.log(`Tekrar için ${delay}ms bekleniyor...`);
await new Promise(resolve => setTimeout(resolve, delay));
// Bir sonraki proxy ile yineleme
return this.request(url, options, attempt + 1);
}
}
// Hataları işleyerek URL'leri topluca işleme
async batchRequest(urls, concurrency = 3) {
const results = [];
const queue = [...urls];
const active = [];
while (queue.length > 0 || active.length > 0) {
// Eş zamanlılık sınırına ulaşana kadar yeni görevleri başlat
while (active.length < concurrency && queue.length > 0) {
const url = queue.shift();
const promise = this.request(url)
.then(data => ({ url, success: true, data }))
.catch(error => ({ url, success: false, error: error.message }))
.finally(() => {
const index = active.indexOf(promise);
if (index > -1) active.splice(index, 1);
});
active.push(promise);
}
// En az bir görevin tamamlanmasını bekleyin
if (active.length > 0) {
const result = await Promise.race(active);
results.push(result);
}
}
return results;
}
}
// Kullanım
const proxyList = [
'http://user1:pass1@proxy1.example.com:8080',
'http://user2:pass2@proxy2.example.com:8080',
'http://user3:pass3@proxy3.example.com:8080'
];
const client = new ResilientProxyClient(proxyList, 3);
// Tek bir istek
client.request('https://api.example.com/data')
.then(data => console.log('Veri:', data))
.catch(error => console.error('Son hata:', error.message));
// Toplu işleme
const urls = [
'https://api.example.com/data/1',
'https://api.example.com/data/2',
'https://api.example.com/data/3',
'https://api.example.com/data/4',
'https://api.example.com/data/5'
];
client.batchRequest(urls, 3)
.then(results => {
const successful = results.filter(r => r.success).length;
const failed = results.filter(r => !r.success).length;
console.log(`Tamamlandı: ${successful} başarılı, ${failed} başarısız`);
console.log('Sonuçlar:', results);
});
Bu uygulama şunları içerir:
- Hata durumunda bir sonraki proxy'ye otomatik geçiş
- Tekrarlar arasında üssel gecikme (1sn, 2sn, 4sn, 8sn, 10sn max)
- Tekrar için karar vermek üzere hata türünün belirlenmesi
- Toplu işleme sırasında eş zamanlılık kontrolü
- Hata ayıklama için ayrıntılı günlüğe kaydetme
En İyi Uygulamalar ve Performans Optimizasyonu
Node.js uygulamalarında proxy ile çalışırken, stabilite ve performansı sağlamak için aşağıdaki önerilere uymalısınız:
1. Bağlantı Yönetimi
Her istek için yeni HTTP ajanları oluşturmak yerine, mevcut olanları yeniden kullanın. Bu, bağlantı kurma üzerindeki yükü azaltır:
const { HttpsProxyAgent } = require('https-proxy-agent');
// Kötü: her istek için ajan oluşturma
async function badExample(url) {
const agent = new HttpsProxyAgent(proxyUrl);
return axios.get(url, { httpsAgent: agent });
}
// İyi: ajanı yeniden kullanma
const agent = new HttpsProxyAgent(proxyUrl);
const axiosInstance = axios.create({
httpsAgent: agent,
httpAgent: agent
});
async function goodExample(url) {
return axiosInstance.get(url);
}
2. Zaman Aşımı Ayarları
Uygulamanın donmasını önlemek için her zaman makul zaman aşımı ayarları yapın:
const axiosInstance = axios.create({
httpsAgent: agent,
timeout: 10000, // Genel zaman aşımı
// Got için zaman aşımı ayarları
// timeout: {
// lookup: 1000, // DNS araması
// connect: 2000, // Proxy'ye bağlanma
// secureConnect: 2000, // SSL el sıkışması
// socket: 5000, // Soket etkinliği
// response: 3000, // İlk yanıt baytını bekleme
// send: 10000, // İsteği gönderme
// request: 15000 // Tüm istek
// }
});
3. Eş Zamanlılık Kontrolü
Aşırı yüklenmeyi önlemek için eş zamanlı istek sayısını sınırlayın:
const pLimit = require('p-limit');
// 5 eş zamanlı istekle sınırlama
const limit = pLimit(5);
async function processUrls(urls) {
const promises = urls.map(url =>
limit(() => axiosInstance.get(url))
);
return Promise.allSettled(promises);
}
4. User-Agent Döngüsü
Proxy döngüsü ile User-Agent döngüsünü birleştirerek daha fazla anonimlik sağlayın:
const userAgents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0'
];
function getRandomUserAgent() {
return userAgents[Math.floor(Math.random() * userAgents.length)];
}
async function fetchWithRandomUA(url) {
return axiosInstance.get(url, {
headers: {
'User-Agent': getRandomUserAgent()
}
});
}
5. İzleme ve Günlüğe Kaydetme
Proxy performansını izlemek için bir izleme sistemi entegre edin:
class ProxyMonitor {
constructor() {
this.stats = new Map();
}
recordRequest(proxyUrl, success, responseTime) {
if (!this.stats.has(proxyUrl)) {
this.stats.set(proxyUrl, {
total: 0,
success: 0,
failed: 0,
totalResponseTime: 0,
avgResponseTime: 0
});
}
const stat = this.stats.get(proxyUrl);
stat.total++;
if (success) {
stat.success++;
stat.totalResponseTime += responseTime;
stat.avgResponseTime = stat.totalResponseTime / stat.success;
} else {
stat.failed++;
}
}
getReport() {
const report = [];
this.stats.forEach((stat, proxyUrl) => {
report.push({
proxy: proxyUrl.replace(/\/\/.*@/, '//***@'),
successRate: ((stat.success / stat.total) * 100).toFixed(2) + '%',
avgResponseTime: stat.avgResponseTime.toFixed(0) + 'ms',
total: stat.total,
success: stat.success,
failed: stat.failed
});
});
return report;
}
}
const monitor = new ProxyMonitor();
// İzleme ile isteklerin sarmalanması
async function monitoredRequest(url, proxyUrl) {
const startTime = Date.now();
try {
const response = await axiosInstance.get(url);
const responseTime = Date.now() - startTime;
monitor.recordRequest(proxyUrl, true, responseTime);
return response.data;
} catch (error) {
const responseTime = Date.now() - startTime;
monitor.recordRequest(proxyUrl, false, responseTime);
throw error;
}
}
// Periyodik rapor
setInterval(() => {
console.table(monitor.getReport());
}, 60000);
6. Proxy Türünün Seçimi
Göreve bağlı olarak proxy türünü seçin:
| Görev | Önerilen Tür | Sebep |
|---|---|---|
| Halka açık verilerin toplu çekimi | Veri merkezi proxy'leri | Yüksek hız, düşük maliyet |
| Sosyal medya ve korumalı platformlarla çalışma | Konut proxy'leri | Gerçek IP'ler, düşük engellenme riski |
| Mobil trafiği taklit etme | Mobil proxy'ler | Mobil operatörlerin IP'leri |
| Standart dışı protokollerle çalışma | SOCKS5 proxy'leri | Her türlü trafiği destekler |
Yüksek anonimlik ve minimum engellenme riski gerektiren görevler için konut proxy'leri kullanılması önerilir. Yüksek hızlı büyük veri çekimi için veri merkezi proxy'leri uygundur.
7. Kimlik Bilgilerinin Güvenliği
Proxy kimlik bilgilerini asla kodda saklamayın. Çevresel değişkenler kullanın:
// .env dosyası
PROXY_HOST=proxy-server.com
PROXY_PORT=8080
PROXY_USERNAME=your-username
PROXY_PASSWORD=your-password
// Kodda
require('dotenv').config();
const proxyUrl = `http://${process.env.PROXY_USERNAME}:${process.env.PROXY_PASSWORD}@${process.env.PROXY_HOST}:${process.env.PROXY_PORT}`;
// Veya proxy listesi için
const proxyList = process.env.PROXY_LIST.split(',').map(proxy => proxy.trim());
Sonuç
Node.js uygulamalarında proxy ayarlamak, veri çekme, otomasyon ve dış API'lerle entegrasyon yapan geliştiriciler için önemli bir beceridir. Bu kılavuzda, proxy ile çalışmanın temel yollarını inceledik: yerleşik modüller aracılığıyla temel ayarlamalardan döngü, hata işleme ve izleme gibi ileri tekniklere kadar.
Hatırlanması gereken ana noktalar:
- HTTP istekleri için kütüphane seçimini göre göre yapın: Axios evrensellik için, Got TypeScript projeleri için, node-fetch tarayıcı API'si ile uyumluluk için
- Standart dışı protokollerle çalışmak için SOCKS5 proxy kullanın ve maksimum esneklik sağlayın
- Yük dağılımı ve engellemelerden kaçınmak için proxy döngüsü uygulayın
- Otomatik tekrarlar ve proxy geçişi ile hata işleme sistemini entegre edin
- Proxy performansını izleyin ve çalışmayanları otomatik olarak hariç tutun
- HTTP ajanlarını yeniden kullanın ve makul zaman aşımı ayarları yapın
- Kimlik bilgilerini kodda değil, çevresel değişkenlerde saklayın
Node.js uygulamalarınız için proxy seçerken görevlerin spesifik özelliklerini dikkate alın. Koruma gerektiren platformların veri çekimi ve IP itibarı konusunda hassas API'lerle çalışmak için konut proxy'leri kullanmanızı öneririz — bunlar, gerçek ev kullanıcılarının IP adreslerini kullanarak yüksek anonimlik sağlar ve engellenme riskini en aza indirir.