GBProxies

如何在Node.js中使用Proxy(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頁面上的proxy登錄信息。端口10000是住宅HTTP;請查看下方每個產品的端口。

提示

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

常見問題

它是否適用於HTTPS網站?

是的。agent會打開一個到目標的CONNECT隧道,因此HTTPS保持端到端加密。

如何在Node.js中使用Proxy(fetch和axios)