You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在单个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@2
    
    代码写法:
    const 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 00:21:26