返回博客

在Node.js应用程序中设置代理:带代码示例的完整指南

详细指南,介绍如何在Node.js中集成代理:从基本设置到高级IP轮换和错误处理技术。

📅2026年2月14日
```html

在开发用于解析、自动化或与 API 交互的 Node.js 应用程序时,通常需要使用代理服务器。这可以绕过地理限制、分散负载并避免 IP 封锁。在本指南中,我们将讨论在 Node.js 中设置代理的所有方法——从基本到高级的轮换和错误处理技术。

Node.js 中代理的基本概念

在 Node.js 中,代理服务器充当您的应用程序与目标服务器之间的中介。当您通过代理发送 HTTP 请求时,您的应用程序首先连接到代理服务器,然后代理服务器将请求重定向到最终地址。这可以隐藏您服务器的真实 IP 地址,并使用代理的 IP 地址。

在 Node.js 中,根据使用的 HTTP 请求库,有几种基本的方法来使用代理。最受欢迎的选项包括:

  • 内置 http/https 模块 — 基本功能,无需额外依赖
  • Axios — 受欢迎的库,提供方便的 API 和 Promise 支持
  • Got — 现代替代方案,支持 TypeScript
  • node-fetch — Node.js 的 Fetch API 实现
  • request — 过时但仍在使用的库(不推荐用于新项目)

代理服务器支持多种协议。在 Node.js 中,最常用的协议包括:

协议 描述 应用
HTTP 用于未加密连接的基本协议 解析、与没有 SSL 的 API 交互
HTTPS 支持 SSL/TLS 加密的代理 安全连接,与受保护的 API 交互
SOCKS5 适用于任何类型流量的通用协议 WebSocket、UDP、复杂场景

对于解析和自动化任务,开发人员通常使用 住宅代理,因为它们具有真实的家庭用户 IP 地址,较少受到目标网站的封锁。

通过内置 http/https 模块设置代理

Node.js 提供了内置的 httphttps 模块来处理 HTTP 请求。要连接代理,可以使用 http-proxy-agenthttps-proxy-agent 库。

首先安装所需的包:

npm install http-proxy-agent https-proxy-agent

使用内置模块的 HTTP 代理示例:

const http = require('http');
const { HttpProxyAgent } = require('http-proxy-agent');

// 代理设置
const proxyUrl = 'http://username:password@proxy-server.com:8080';
const agent = new HttpProxyAgent(proxyUrl);

// 请求选项
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'
  }
};

// 执行请求
const req = http.request(options, (res) => {
  let data = '';
  
  res.on('data', (chunk) => {
    data += chunk;
  });
  
  res.on('end', () => {
    console.log('Response:', data);
  });
});

req.on('error', (error) => {
  console.error('Request failed:', error.message);
});

req.end();

对于 HTTPS 连接,请使用 https-proxy-agent

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('Secure response:', data);
  });
}).on('error', (error) => {
  console.error('HTTPS request failed:', error.message);
});

这种方法提供了对请求的最大控制,但需要更多代码来处理 Promise 和错误。对于大多数任务,使用专门的库会更方便。

在 Axios 库中使用代理

Axios 是 Node.js 中最受欢迎的 HTTP 请求库之一。它提供了方便的 API 来设置代理,并自动处理 Promise。

安装 Axios:

npm install axios

在 Axios 中的基本代理设置如下:

const axios = require('axios');

// 方法 1:在请求配置中设置代理
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('Data:', response.data);
})
.catch(error => {
  console.error('Error:', error.message);
});

为了多次使用相同的代理设置,可以创建一个带有预设配置的 Axios 实例:

const axios = require('axios');

// 创建带有代理设置的实例
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'
  }
});

// 使用实例
async function fetchData() {
  try {
    const response = await axiosWithProxy.get('https://api.example.com/data');
    console.log('Response:', response.data);
    return response.data;
  } catch (error) {
    console.error('Request failed:', error.message);
    throw error;
  }
}

fetchData();

通过 CONNECT 方法与 HTTPS 代理一起使用,可以使用额外的代理:

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
});

// 使用
axiosInstance.get('https://api.example.com/secure-data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error.message));

Axios 自动处理重定向,并支持拦截器用于日志记录和错误处理,这使其成为积极使用代理的项目的绝佳选择。

在 got 和 node-fetch 中设置代理

Got 是 Axios 的现代替代方案,具有出色的 TypeScript 支持和高级错误处理功能。Node-fetch 实现了 Node.js 的标准 Fetch API。

在 Got 中使用代理

安装 Got 和所需的代理:

npm install got https-proxy-agent

在 Got 中设置代理的示例:

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)
};

// 创建带有代理的 Got 实例
const gotWithProxy = got.extend({
  agent: agent,
  timeout: {
    request: 10000
  },
  retry: {
    limit: 3,
    methods: ['GET', 'POST']
  }
});

// 使用
async function fetchWithGot() {
  try {
    const response = await gotWithProxy('https://api.example.com/data');
    console.log('Response:', JSON.parse(response.body));
  } catch (error) {
    console.error('Got request failed:', error.message);
  }
}

fetchWithGot();

在 node-fetch 中使用代理

Node-fetch 需要明确设置代理以使用代理:

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 error! status: ${response.status}`);
    }
    
    const data = await response.json();
    console.log('Data:', data);
    return data;
  } catch (error) {
    console.error('Fetch failed:', error.message);
    throw error;
  }
}

fetchWithProxy();

Got 提供了更丰富的开箱即用功能(自动重试、超时、错误处理),而 node-fetch 更接近标准 Fetch API,适合熟悉浏览器 JavaScript 的开发人员。

通过 socks-proxy-agent 连接 SOCKS5 代理

SOCKS5 是一种通用的代理协议,工作在比 HTTP/HTTPS 更低的层次。它支持任何类型的流量,包括 UDP 和 WebSocket 连接。要在 Node.js 中使用 SOCKS5,可以使用 socks-proxy-agent 库。

安装所需的包:

npm install socks-proxy-agent

使用 SOCKS5 代理与不同库的示例:

const { SocksProxyAgent } = require('socks-proxy-agent');
const https = require('https');

// 设置带有认证的 SOCKS5 代理
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 response:', data);
  });
}).on('error', (error) => {
  console.error('SOCKS5 request failed:', error.message);
});

使用 SOCKS5 与 Axios:

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('Data via SOCKS5:', response.data);
    return response.data;
  } catch (error) {
    console.error('SOCKS5 request error:', error.message);
    throw error;
  }
}

fetchViaSocks5();

SOCKS5 代理特别适合需要处理非标准协议或需要最大灵活性的任务。许多提供商提供 支持 SOCKS5 的移动代理,这使得模拟移动流量以与移动 API 交互成为可能。

实现代理轮换以分散负载

在解析大量数据或与有请求数量限制的 API 交互时,需要使用代理轮换。这可以将请求分散到多个代理服务器上,避免封锁。

简单的代理轮换实现示例:

const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');

class ProxyRotator {
  constructor(proxyList) {
    this.proxyList = proxyList;
    this.currentIndex = 0;
  }
  
  // 按循环方式获取下一个代理
  getNextProxy() {
    const proxy = this.proxyList[this.currentIndex];
    this.currentIndex = (this.currentIndex + 1) % this.proxyList.length;
    return proxy;
  }
  
  // 获取随机代理
  getRandomProxy() {
    const randomIndex = Math.floor(Math.random() * this.proxyList.length);
    return this.proxyList[randomIndex];
  }
  
  // 创建带有当前代理的 Axios 实例
  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'
      }
    });
  }
}

// 代理列表
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);

// 使用轮换
async function fetchWithRotation(url) {
  const axiosInstance = rotator.createAxiosInstance();
  
  try {
    const response = await axiosInstance.get(url);
    console.log('Success with proxy');
    return response.data;
  } catch (error) {
    console.error('Request failed:', error.message);
    throw error;
  }
}

// 大规模解析示例
async function massiveParsing(urls) {
  const results = [];
  
  for (const url of urls) {
    try {
      const data = await fetchWithRotation(url);
      results.push({ url, success: true, data });
      
      // 请求之间的延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
    } catch (error) {
      results.push({ url, success: false, error: error.message });
    }
  }
  
  return results;
}

// 启动解析
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('Parsing results:', results))
  .catch(error => console.error('Parsing error:', error));

更高级的示例,跟踪代理状态并自动排除不工作的代理:

class AdvancedProxyRotator {
  constructor(proxyList, maxFailures = 3) {
    this.proxyList = proxyList.map(url => ({
      url,
      failures: 0,
      active: true,
      lastUsed: null
    }));
    this.maxFailures = maxFailures;
    this.currentIndex = 0;
  }
  
  // 获取活动代理
  getActiveProxy() {
    const activeProxies = this.proxyList.filter(p => p.active);
    
    if (activeProxies.length === 0) {
      throw new Error('没有可用的活动代理');
    }
    
    // 查找使用时间最长的代理
    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;
  }
  
  // 标记代理为成功
  markSuccess(proxyUrl) {
    const proxy = this.proxyList.find(p => p.url === proxyUrl);
    if (proxy) {
      proxy.failures = 0;
    }
  }
  
  // 标记代理为失败
  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(`代理 ${proxyUrl} 在 ${proxy.failures} 次失败后被停用`);
      }
    }
  }
  
  // 创建带有轮换的 Axios 实例
  async createAxiosInstance() {
    const proxy = this.getActiveProxy();
    const agent = new HttpsProxyAgent(proxy.url);
    
    return {
      instance: axios.create({
        httpsAgent: agent,
        timeout: 10000
      }),
      proxyUrl: proxy.url
    };
  }
  
  // 获取代理统计信息
  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(/\/\/.*@/, '//***@'), // 隐藏凭据
        active: p.active,
        failures: p.failures
      }))
    };
  }
}

// 使用高级轮换器
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;
  }
}

// 定期输出统计信息
setInterval(() => {
  console.log('代理统计信息:', advancedRotator.getStats());
}, 30000);

这种系统会自动将不工作的代理排除在轮换之外,并在活动服务器之间均匀分配负载。在处理大量数据时,这一点至关重要。

错误处理和自动切换代理

在使用代理时,错误是不可避免的:超时、连接拒绝、目标服务器的封锁。正确的错误处理和自动切换到其他代理可以提高应用程序的可靠性。

实现自动重试和切换代理的系统示例:

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;
  }
  
  // 获取下一个代理
  getNextProxy() {
    const proxy = this.proxyList[this.currentProxyIndex];
    this.currentProxyIndex = (this.currentProxyIndex + 1) % this.proxyList.length;
    return proxy;
  }
  
  // 确定错误类型
  isRetryableError(error) {
    // 应该重试请求的错误
    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;
  }
  
  // 执行带有自动重试的请求
  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(`尝试 ${attempt}/${this.maxRetries} 使用代理: ${proxyUrl.replace(/\/\/.*@/, '//***@')}`);
      const response = await axios.get(url, config);
      console.log(`尝试 ${attempt} 成功`);
      return response.data;
    } catch (error) {
      console.error(`尝试 ${attempt} 失败: ${error.message}`);
      
      // 如果达到重试限制
      if (attempt >= this.maxRetries) {
        console.error(`对于 ${url} 达到最大重试次数 (${this.maxRetries})`);
        throw error;
      }
      
      // 如果错误不可重试
      if (!this.isRetryableError(error)) {
        console.error(`不可重试的错误: ${error.message}`);
        throw error;
      }
      
      // 在重试之前进行指数延迟
      const delay = Math.min(1000 * Math.pow(2, attempt - 1), 10000);
      console.log(`等待 ${delay}ms 后重试...`);
      await new Promise(resolve => setTimeout(resolve, delay));
      
      // 使用下一个代理递归重试
      return this.request(url, options, attempt + 1);
    }
  }
  
  // 批量处理 URL 并处理错误
  async batchRequest(urls, concurrency = 3) {
    const results = [];
    const queue = [...urls];
    const active = [];
    
    while (queue.length > 0 || active.length > 0) {
      // 启动新任务直到达到并发限制
      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);
      }
      
      // 等待至少一个任务完成
      if (active.length > 0) {
        const result = await Promise.race(active);
        results.push(result);
      }
    }
    
    return results;
  }
}

// 使用
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);

// 单个请求
client.request('https://api.example.com/data')
  .then(data => console.log('Data:', data))
  .catch(error => console.error('Final error:', error.message));

// 批量处理
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(`完成: ${successful} 成功, ${failed} 失败`);
    console.log('结果:', results);
  });

此实现包括:

  • 在发生错误时自动切换到下一个代理
  • 在重试之间进行指数延迟 (1s, 2s, 4s, 8s, 最大 10s)
  • 确定错误类型以决定是否重试
  • 在批量处理时控制并发
  • 详细日志记录以进行调试

最佳实践和性能优化

在 Node.js 应用程序中使用代理时,应遵循以下建议以确保稳定性和性能:

1. 管理连接

重用 HTTP 代理,而不是为每个请求创建新的。这可以减少建立连接的开销:

const { HttpsProxyAgent } = require('https-proxy-agent');

// 不好:为每个请求创建代理
async function badExample(url) {
  const agent = new HttpsProxyAgent(proxyUrl);
  return axios.get(url, { httpsAgent: agent });
}

// 好:重用代理
const agent = new HttpsProxyAgent(proxyUrl);
const axiosInstance = axios.create({
  httpsAgent: agent,
  httpAgent: agent
});

async function goodExample(url) {
  return axiosInstance.get(url);
}

2. 设置超时

始终设置合理的超时以防止应用程序挂起:

const axiosInstance = axios.create({
  httpsAgent: agent,
  timeout: 10000, // 总超时
  // Got 的详细超时设置
  // timeout: {
  //   lookup: 1000,    // DNS 查找
  //   connect: 2000,   // 连接到代理
  //   secureConnect: 2000, // SSL 握手
  //   socket: 5000,    // 套接字不活动
  //   response: 3000,  // 等待第一个字节的响应
  //   send: 10000,     // 发送请求
  //   request: 15000   // 整个请求
  // }
});

3. 控制并发

限制同时请求的数量以防止过载:

const pLimit = require('p-limit');

// 限制为 5 个同时请求
const limit = pLimit(5);

async function processUrls(urls) {
  const promises = urls.map(url => 
    limit(() => axiosInstance.get(url))
  );
  
  return Promise.allSettled(promises);
}

4. User-Agent 轮换

将代理轮换与 User-Agent 轮换结合使用以提高匿名性:

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. 监控和日志记录

实施监控系统以跟踪代理的性能:

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();

// 带监控的请求包装
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;
  }
}

// 定期报告
setInterval(() => {
  console.table(monitor.getReport());
}, 60000);

6. 选择代理类型

根据任务选择代理类型:

任务 推荐类型 原因
大规模解析公共数据 数据中心代理 高速,低价格
与社交媒体和保护平台交互 住宅代理 真实 IP,低封锁风险
模拟移动流量 移动代理 移动运营商的 IP
与非标准协议交互 SOCKS5 代理 支持任何流量

对于需要高匿名性和最低封锁风险的任务,建议使用 住宅代理。对于高速解析大量数据,建议使用 数据中心代理

7. 凭据安全性

永远不要在代码中存储代理凭据。使用环境变量:

// .env 文件
PROXY_HOST=proxy-server.com
PROXY_PORT=8080
PROXY_USERNAME=your-username
PROXY_PASSWORD=your-password

// 在代码中
require('dotenv').config();

const proxyUrl = `http://${process.env.PROXY_USERNAME}:${process.env.PROXY_PASSWORD}@${process.env.PROXY_HOST}:${process.env.PROXY_PORT}`;

// 或者对于代理列表
const proxyList = process.env.PROXY_LIST.split(',').map(proxy => proxy.trim());

结论

在 Node.js 应用程序中设置代理是开发人员处理解析、自动化和与外部 API 集成的重要技能。在本指南中,我们讨论了所有主要的代理使用方法:从通过内置模块的基本设置到高级的轮换、错误处理和监控技术。

需要记住的关键点:

  • 根据任务选择 HTTP 请求库:Axios 用于通用性,Got 用于 TypeScript 项目,node-fetch 用于与浏览器 API 的兼容性
  • 使用 SOCKS5 代理处理非标准协议和最大灵活性
  • 实现代理轮换以分散负载并避免封锁
  • 实施错误处理系统,自动重试和切换代理
  • 监控代理性能并自动排除不工作的代理
  • 重用 HTTP 代理并设置合理的超时
  • 将凭据存储在环境变量中,而不是代码中

在为您的 Node.js 应用程序选择代理时,请考虑任务的特性。对于解析受保护的平台和与对 IP 声誉敏感的 API 交互,建议使用 住宅代理——它们提供高水平的匿名性和最低的封锁风险,因为使用的是家庭用户的真实 IP 地址。

```