如何在单个Node.js文件中调用fetch方法?运行报错求助
在Node.js单文件中正确使用fetch方法
你报错的核心原因是:你用的fetch包的fetchUrl方法不返回Promise对象,它是基于回调的异步API,直接调用后用.then()肯定会报错——因为返回值里找不到then方法。
下面是几种可行的解决方式:
方法1:用Node.js内置fetch(推荐,Node.js 18+)
从Node.js 18版本开始,官方已经内置了和浏览器一致的标准fetch API,不需要安装任何第三方包,直接写代码:
fetch("https://jsonplaceholder.typicode.com/todos/1") .then(res => res.json()) .then(d => console.log(d)) .catch(err => console.error(err)); // 记得加上错误捕获
执行命令还是node fetch.js,直接运行即可。
方法2:使用node-fetch包(兼容旧版Node)
如果你的Node版本低于18,需要安装node-fetch包,注意不同版本的导入方式:
- 安装v2版本(适配CommonJS,用require导入):
代码写法:npm install node-fetch@2const fetch = require('node-fetch'); fetch("https://jsonplaceholder.typicode.com/todos/1") .then(res => res.json()) .then(d => console.log(d)) .catch(err => console.error(err)); - 安装v3版本(适配ES模块,需调整文件格式):
要么把文件后缀改成npm install node-fetch.mjs,要么在项目的package.json中添加"type": "module",然后用import导入:import fetch from 'node-fetch'; fetch("https://jsonplaceholder.typicode.com/todos/1") .then(res => res.json()) .then(d => console.log(d)) .catch(err => console.error(err));
方法3:继续使用你原来的fetch包(不推荐)
你最初安装的fetch包(注意和node-fetch不是同一个),它的fetchUrl必须用回调写法:
const fetchUrl = require("fetch").fetchUrl; fetchUrl("https://jsonplaceholder.typicode.com/todos/1", (error, meta, body) => { if (error) { console.error(error); return; } const data = JSON.parse(body.toString()); console.log(data); });
这种写法不如Promise/async await直观,所以更推荐前面两种方案。
内容的提问来源于stack exchange,提问作者pawelek91
相关产品推荐
相关产品推荐

