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在近期还修复过相关的漏洞,使用者需要额外关注,尽可能选用最新稳定版本。

相关推荐
excel1 天前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel1 天前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼1 天前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping1 天前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙1 天前
[译] Composition in CSS
前端·css
白水清风1 天前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix1 天前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户22152044278001 天前
new、原型和原型链浅析
前端·javascript
阿星做前端1 天前
coze源码解读: space develop 页面
前端·javascript
叫我小窝吧1 天前
Promise 的使用
前端·javascript