Node.js 代码示例
以下示例展示如何用 Node.js 获取并使用短效代理 IP。
写法 A:直接使用复制来的链接
Section titled “写法 A:直接使用复制来的链接”最短路径。在用户中心【短效代理】→【生成API】→【复制链接】拿到完整地址,直接请求:
// 从用户中心【复制链接】得到的完整地址const TARGET_URL = 'https://api.beesproxy.com/api/v1/proxies/?order_id=...&format=json&ip_num=10&user_token=...';
async function main() { const res = await fetch(TARGET_URL);
// 出错时 HTTP 状态码同样是 200,不要用 res.ok 判断 const data = await res.json(); if (data.code !== 0) { throw new Error(`获取代理失败:[${data.code}] ${data.message}`); }
for (const p of data.result) { console.log(`${p.host}:${p.port} (${p.city_cn})`); }}
main();写法 B:在代码里拼接参数
Section titled “写法 B:在代码里拼接参数”需要根据业务动态调整 ip_num 时用这种写法:
const API_URL = 'https://api.beesproxy.com/api/v1/proxies/';const ORDER_ID = 'YOUR_ORDER_ID'; // 用户中心【短效代理】页const USER_TOKEN = 'YOUR_USER_TOKEN'; // 用户中心【总览】页
async function getProxies(ipNum = 10) { const params = new URLSearchParams({ order_id: ORDER_ID, user_token: USER_TOKEN, format: 'json', ip_num: String(ipNum), });
const res = await fetch(`${API_URL}?${params}`); const data = await res.json();
if (data.code !== 0) { throw new Error(`获取代理失败:[${data.code}] ${data.message}`); } return data.result;}
getProxies(5).then((proxies) => { proxies.forEach((p) => console.log(`${p.host}:${p.port} (${p.city_cn})`));});ip_num 超过订单的 IP 提取数时会被静默截断,代理池不足时也可能少给——不要假设返回条数一定等于请求条数。
使用代理 IP 发送请求
Section titled “使用代理 IP 发送请求”Node.js 内置的 fetch 不直接支持 HTTP 代理,推荐用 axios 配合 https-proxy-agent:
npm install axios https-proxy-agentconst axios = require('axios');const { HttpsProxyAgent } = require('https-proxy-agent');
async function useProxy(proxyHost, proxyPort, targetUrl) { const agent = new HttpsProxyAgent(`http://${proxyHost}:${proxyPort}`); const response = await axios.get(targetUrl, { httpsAgent: agent, timeout: 10000 }); return response.data;}
getProxies(1).then(async (proxies) => { const proxy = proxies[0]; console.log(await useProxy(proxy.host, proxy.port, 'https://httpbin.org/ip'));});这一步连不上,通常是白名单问题,见 白名单配置。
轮询使用多个代理
Section titled “轮询使用多个代理”async function fetchWithRotation(urls, ipNum = 10) { const proxies = await getProxies(ipNum); if (proxies.length === 0) { throw new Error('代理池暂时没有可用 IP,请稍后重试'); }
const results = []; for (let i = 0; i < urls.length; i++) { const proxy = proxies[i % proxies.length]; const agent = new HttpsProxyAgent(`http://${proxy.host}:${proxy.port}`);
try { const resp = await axios.get(urls[i], { httpsAgent: agent, timeout: 10000 }); results.push({ url: urls[i], status: resp.status }); } catch (err) { results.push({ url: urls[i], error: err.message }); } }
return results;}