You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Node.js 18原生Fetch请求代理配置方案咨询:是否需依赖第三方包及最优实现代码

Great question! Let's break this down for you clearly—Node.js 18's native fetch is a total game-changer, but proxy setup can feel confusing at first.


1. Can you configure proxy for native Fetch without extra dependencies?

Absolutely! You have two reliable, dependency-free options:

Option 1: Use environment variables (simplest approach)

Node.js's native fetch (powered by the Undici library under the hood) automatically honors standard proxy environment variables. This is perfect if you don't need to hardcode proxy settings in your code.

Just set these variables before running your script:

# Linux/macOS terminal
export HTTP_PROXY=http://your-proxy-server:port
export HTTPS_PROXY=http://your-proxy-server:port
export NO_PROXY=localhost,127.0.0.1,your-internal-domain.com
node your-fetch-script.js

# Windows Command Prompt
set HTTP_PROXY=http://your-proxy-server:port
set HTTPS_PROXY=http://your-proxy-server:port
set NO_PROXY=localhost,127.0.0.1,your-internal-domain.com
node your-fetch-script.js

# Windows PowerShell
$env:HTTP_PROXY = "http://your-proxy-server:port"
$env:HTTPS_PROXY = "http://your-proxy-server:port"
$env:NO_PROXY = "localhost,127.0.0.1,your-internal-domain.com"
node your-fetch-script.js

Once set, every fetch() call in your code will route through the proxy automatically—no code changes required.

Option 2: Code-level configuration with built-in Undici

Node.js 18 bundles Undici (the library that powers native fetch) as a core module, so you can use its ProxyAgent directly without installing anything extra. This is ideal if you need to set proxy settings dynamically in your code.

Here's a working example:

// Import ProxyAgent from the built-in undici module
const { ProxyAgent } = require('undici');

async function fetchWithProxy() {
  // Initialize the proxy agent with your proxy URL
  const proxyAgent = new ProxyAgent('http://your-proxy-server:port');

  // Pass the agent via the `dispatcher` option in fetch
  const response = await fetch('https://api.example.com/data', {
    dispatcher: proxyAgent,
    // Optional: Add custom headers or other fetch options
    headers: {
      'Accept': 'application/json'
    }
  });

  if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
  }

  const data = await response.json();
  console.log('Fetched data:', data);
}

// Run the function and handle errors
fetchWithProxy().catch(err => console.error('Fetch failed:', err));

2. If you need third-party packages (for advanced use cases)

For complex proxy scenarios—like SOCKS proxies, proxy authentication with custom headers, or legacy proxy setups—the most robust and widely used packages are:

  • https-proxy-agent: For HTTP/HTTPS proxies (seamless with Node.js's core modules and fetch)
  • socks-proxy-agent: For SOCKS v4/v5 proxies

Example with https-proxy-agent

First install the package:

npm install https-proxy-agent

Then implement it with fetch:

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

async function fetchWithThirdPartyProxy() {
  const proxyAgent = new HttpsProxyAgent('http://your-proxy-server:port');

  // Wrap the third-party agent in an Undici dispatcher for fetch compatibility
  const response = await fetch('https://api.example.com/data', {
    dispatcher: new (require('undici').Agent)({
      connect: {
        agent: proxyAgent
      }
    })
  });

  const data = await response.json();
  console.log('Fetched data:', data);
}

fetchWithThirdPartyProxy().catch(err => console.error('Error:', err));

Example with socks-proxy-agent

Install the package first:

npm install socks-proxy-agent

Then use it with fetch:

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

async function fetchWithSocksProxy() {
  const proxyAgent = new SocksProxyAgent('socks://your-socks-proxy:port');

  const response = await fetch('https://api.example.com/data', {
    dispatcher: new (require('undici').Agent)({
      connect: {
        agent: proxyAgent
      }
    })
  });

  const data = await response.json();
  console.log('Fetched data:', data);
}

fetchWithSocksProxy().catch(err => console.error('Error:', err));

内容的提问来源于stack exchange,提问作者bruxs

火山引擎 最新活动