GBProxies

如何在Node.js (fetch與axios)中使用代理

Node.js 18及以上版本透過undici提供fetch。ProxyAgent會使用您的登入資訊將每個請求通過閘道發送。

步驟

  1. 使用npm install undici安裝undici
  2. 使用閘道URL和您的登入資訊建立ProxyAgent
  3. 將其作為dispatcher傳遞給fetch
  4. 需要時在使用者名稱中添加國家代碼或會話ID

範例程式碼

import { ProxyAgent, fetch } from "undici";

const agent = new ProxyAgent({
  uri: "http://gw.gbproxies.cc:10000",
  token: "Basic " + Buffer.from("USERNAME-cc-de:PASSWORD").toString("base64"),
});
const r = await fetch("https://api.ipify.org?format=json", { dispatcher: agent });
console.log(await r.json());

將USERNAME和PASSWORD替換為控制台Proxies頁面中的代理登入資訊。端口10000是住宅HTTP代理;各產品端口請見下方。

提示

  • 使用axios時,設定proxy: { protocol: "http", host, port, auth: { username, password } }
  • 當需要同時使用多個固定IP時,為每個會話ID建立一個agent

常見問題

是否支援HTTPS網站?

支援。agent會建立到目標的CONNECT通道,因此HTTPS保持端到端加密。

如何在Node.js (fetch與axios)中使用代理