ES 方式开发nodejs

241 阅读1分钟

我们默认开发nodejs都是cms的方式,今天引入node-fetch,发现node-fetch@3.x只能通过es模块的方式引入,如果要使用cms模块要使用node-fetch@2.x才可以。

私以为es是标准,是未来,nodejs目前也是支持的,那我们就用es的方式来写代码吧。

关键需要设置一下package.json里面的"type": "module"即可,他们跟原来的一样。

准备项目

下面pnpm命令可以换成npm,但是pnpm有优势,我的项目基本上能用pnpm都会用pnpm,有一个特例,npm init -y 这个命令不能用pnpm

mkdir node-fetch-demo
cd node-fetch-demo
npm init -y
pnpm add node-fetch

编写index.js

import fetch from 'node-fetch';

const testPost = async () => {
  const response = await fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' });
  const data = await response.json();

  console.log(data);
};
testPost(); // 编译错误

运行发现错误:

Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

image.png

解决:如上面提示所说,在package.json设置"type": "module"

重新运行,得到如下输出结果:

image.png

这里注意,发送post请求时,body属性的值需要时字符串,如果是一个对象,需要我们自己JSON.stringify一下,例如JSON.stringify({ name: 'lily', age: 18 })

这里说下为什么突然使用 node-fetch, 主要是我们的业务需要我们做一个nodejs中转服务,去请求AI算法后台的python服务然后把输出结果使用Http传给前端,不想用axios,用node-fetch很轻量,很简便,就用它了。