Node.js在哪个版本起可以使用原生Fetch API?

大家好,我是老纪。

经常关注前端与Node.js发展的同学,想必知道Node.js这几年来正在努力做 Web API 的兼容性支持,比如说 Web Crypto、Fetch、Web Stream、WebAssembly、Web Worker等等,这些原属于Deno的竞争优势,现在在逐渐被Node.js拉平。

那么,我们从什么版本起可以使用原生的Fetch API呢?

答案是:v18.0.0

这是Node.js API文档的截图:

表明Fetch API是在v17.5.0v16.15.0起添加的,但是需要额外使用一个flag(--experimental-fetch)来开启,只不过会打印警告内容,表示并不稳定:

bash 复制代码
> node --experimental-fetch index.js

Node: v17.5.0
(node:40605) ExperimentalWarning: Fetch is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
(node:40605) ExperimentalWarning: buffer.Blob is an experimental feature. This feature could change at any time

而从v18.0.0起,就可以不使用这个flag标记,直接使用Fetch API了。只是仍有警告出现:

bash 复制代码
> node index.js

Node: v18.0.0
(node:44974) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)

在Fetch API的MDN页面的浏览器支持情况里,也把Node.js给加了进去:

那么什么时候Fetch API开始稳定下来呢?

答案是:v21

详见Node.js官方的发版说明

这次什么警告都没有了:

bash 复制代码
> node index.js

Node: v21.0.0

从这个版本起,我们就可以彻底摆脱axiosnode-fetch这些第三方包了。

以上测试代码为:

javascript 复制代码
const getPosts = async () => {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts");
  const data = await res.json();
  console.log(data[0].title);
};

console.log("Node:", process.version);
getPosts();

TIPS

虽然从Node.js v18起就可以使用Fetch API,但我们尽可能使用新版本的Node.js,比如在2月14日(情人节当天),Node.js的新版本还修复了一个漏洞

漏洞是这样的:

之前版本还修复过这些漏洞:

总结

Node.js的Fetch APIv17.5.0v16.15.0起,需要额外的--experimental-fetch标记才能启用。从v18起可以直接使用而无需开启flag,但仍有警告提示,直到v21才正式稳定下来,不再产生警告。值得注意的是,Node.js在近期还修复过相关的漏洞,使用者需要额外关注,尽可能选用最新稳定版本。

相关推荐
li357410 小时前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj11 小时前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
excel11 小时前
CNN 分层详解:卷积、池化到全连接的作用与原理
前端
excel11 小时前
CNN 多层设计详解:从边缘到高级特征的逐层学习
前端
西陵12 小时前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
大前端helloworld12 小时前
从初中级如何迈入中高级-其实技术只是“入门卷”
前端·面试
Cosmoshhhyyy13 小时前
Node.js 18+安装及Claude国内镜像使用、idea中claude插件下载指南
node.js
东风西巷14 小时前
Balabolka:免费高效的文字转语音软件
前端·人工智能·学习·语音识别·软件需求
萌萌哒草头将军14 小时前
10个 ES2025 新特性速览!🚀🚀🚀
前端·javascript·vue.js