DEBUG.WIKI
野草云;香港 200Mbps 峰值;不限月流量 · BGP VPS;查看套餐 →
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS

解决 Node.js 报错 ReferenceError: fetch is not defined 的排查指南

排查与解决旧版 Node.js 执行网络请求提示 ReferenceError: fetch is not defined 的完整方案。

问题现象

在 Node.js 脚本或后端服务中直接调用标准的 fetch() 函数请求外部 API 时,程序抛出未定义异常并崩溃:

/app/server.js:8
const response = await fetch('https://api.example.com/data');
                       ^

ReferenceError: fetch is not defined
    at fetchData (/app/server.js:8:24)
    at Object.<anonymous> (/app/server.js:15:1)

触发根因

  1. Node.js 运行时版本过旧(低于 Node.js 18):在 Node.js 18.0.0 之前,Node.js 核心并没有内置 Web 标准的 fetch API,只有浏览器端才拥有全局 fetch。
  2. 在 Node.js 14 或 Node.js 16 等旧版 LTS 环境中直接调用了全局 fetch。

解决步骤与操作命令

步骤一:升级 Node.js 至 18+ 或 20+ LTS(推荐最佳方案)

自 Node.js 18 起,官方基于高性能的 undici 引擎全面原生内置了全局 fetch,无需安装任何第三方库。 使用 nvm 升级 Node 版本:

nvm install 20
nvm use 20

验证当前版本支持原生 fetch:

node -e "fetch('https://httpbin.org/get').then(res => console.log('Fetch native OK:', res.status))"

步骤二:若必须停留在旧版 Node.js,安装 node-fetch 并在入口引入

若项目因兼容性无法升级 Node 版本,安装轻量 polyfill 库:

npm install node-fetch@2

在代码头部显式导入:

// 对于 CommonJS:
const fetch = require('node-fetch');

async function getData() {
    const res = await fetch('https://api.example.com/data');
    const data = await res.json();
    return data;
}

步骤三:改用 Axios 等成熟跨平台网络库

npm install axios

验证确认

在终端重新运行业务脚本:

node /app/server.js

服务顺畅完成网络请求并成功解析返回数据,未再抛出 ReferenceError: fetch is not defined 异常。