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

相关推荐
apcipot_rain4 小时前
【应用密码学】实验五 公钥密码2——ECC
前端·数据库·python
ShallowLin4 小时前
vue3学习——组合式 API:生命周期钩子
前端·javascript·vue.js
Nejosi_念旧4 小时前
Vue API 、element-plus自动导入插件
前端·javascript·vue.js
互联网搬砖老肖4 小时前
Web 架构之攻击应急方案
前端·架构
pixle05 小时前
Vue3 Echarts 3D饼图(3D环形图)实现讲解附带源码
前端·3d·echarts
麻芝汤圆5 小时前
MapReduce 入门实战:WordCount 程序
大数据·前端·javascript·ajax·spark·mapreduce
juruiyuan1117 小时前
FFmpeg3.4 libavcodec协议框架增加新的decode协议
前端
Vone_667 小时前
node.js 邮箱验证服务器搭建
运维·服务器·node.js
Peter 谭7 小时前
React Hooks 实现原理深度解析:从基础到源码级理解
前端·javascript·react.js·前端框架·ecmascript
程序员拂雨8 小时前
HTTP和HTTPS模块
http·https·node.js