快速回答
如何在 Node.js 中使用美国城市代理?
为 http://gw.metroproxies.com:7777 创建一个 undici ProxyAgent,使用城市用户名(如 USERNAME-country-us-state-fl-city-orlando),并将其作为 fetch 的 dispatcher 传入;Playwright 在其 proxy 选项中接受相同的值。MetroProxies 在 US$0.50/GB(2026 年 10 月)起的每个套餐中都包含城市、ZIP 和 ASN 定位。无需 KYC;支持加密货币。
import { ProxyAgent, fetch } from 'undici';
const user = 'USERNAME-country-us-state-fl-city-orlando';
const agent = new ProxyAgent({
uri: 'http://gw.metroproxies.com:7777',
token: 'Basic ' + Buffer.from(`${user}:PASSWORD`).toString('base64'),
});
const res = await fetch('https://ipinfo.io/json', { dispatcher: agent, signal: AbortSignal.timeout(30000) });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
console.log(await res.json());
await agent.close();
import { ProxyAgent, fetch } from 'undici';
const cities = [['fl', 'orlando'], ['fl', 'tampa'], ['ga', 'atlanta']];
for (const [state, city] of cities) {
const user = `USERNAME-country-us-state-${state}-city-${city}`;
const agent = new ProxyAgent({
uri: 'http://gw.metroproxies.com:7777',
token: 'Basic ' + Buffer.from(`${user}:PASSWORD`).toString('base64'),
});
try {
const res = await fetch('https://ipinfo.io/json', { dispatcher: agent, signal: AbortSignal.timeout(30000) });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const info = await res.json();
console.log(city, '->', info.ip, info.city, info.region);
} catch (err) {
console.log(city, 'failed:', err.message);
} finally {
await agent.close();
}
}
import { chromium } from 'playwright';
const browser = await chromium.launch({
proxy: {
server: 'http://gw.metroproxies.com:7777',
username: 'USERNAME-country-us-state-fl-city-miami-session-mia01-ttl-15',
password: 'PASSWORD',
},
});
const context = await browser.newContext({ timezoneId: 'America/New_York', locale: 'en-US' });
const page = await context.newPage();
await page.goto('https://ipinfo.io/json', { timeout: 60000 });
console.log(await page.textContent('body'));
await browser.close();
在 Node.js 中需要注意什么?
- Keep-alive: 一个
ProxyAgent会复用连接,因此在轮换模式下,只要连接保持打开,它就会保持同一个出口 IP。为每个城市创建一个 agent,或关闭它,以获取新 IP。 - 时区和区域设置: Playwright 的
timezoneId和locale选项使浏览器与城市匹配;每个城市页面都给出了其 IANA 时区(迈阿密:America/New_York)。 - SOCKS5: Chromium 不会向 SOCKS5 代理发送用户名;在浏览器中使用 HTTP 端口。
- 超时: fetch 中为
AbortSignal.timeout(),Playwright 中为timeout。 - 速率: 对每个站点的请求保持适度,并遵守其 robots.txt 和条款。
接下来该去哪里?
人们还常问关于 Node.js 的哪些问题?
我需要哪个 Node.js 版本?
Node.js 18 或更高版本,用于 AbortSignal.timeout 以及 .mjs 文件中的顶层 await。用 npm install undici 安装 undici,用 npm install playwright 安装 Playwright。
Puppeteer 也能用吗?
可以:用 --proxy-server=http://gw.metroproxies.com:7777 启动,并在首次导航前调用 page.authenticate({ username, password })。
这些示例是针对网关运行的吗?
它们已用 node --check 做过语法检查,其中 USERNAME 和 PASSWORD 为占位符。请用你自己的凭据运行。