(已关闭)TypeError: fetch is not a function,我做错了啥?

Posted

技术标签:

【中文标题】(已关闭)TypeError: fetch is not a function,我做错了啥?【英文标题】:(CLOSED) TypeError: fetch is not a function, What did I do wrong?(已关闭)TypeError: fetch is not a function,我做错了什么? 【发布时间】:2021-11-19 22:28:23 【问题描述】:

我正在尝试使用 node-fetch 来获取包含此 JSON 文件的网站,我可以将其用于我的不和谐机器人。

代码(JS):

const fetch = import("node-fetch")

// some code until

data = ""
        try 
            data = await fetch(`http://meme-api.herokuapp.com/gimme/$subreddit.toLowerCase())`).then(res => res.json)
            errored = false
         catch (error) 
            throw error;
        

错误提示:

TypeError: fetch is not a function

我该如何解决这个问题?

仅供参考,使用 require() 会导致如下错误:

const fetch = require("node-fetch")
              ^

Error [ERR_REQUIRE_ESM]: require() of ES Module F:\Users\Basil Atif\Folders\VsauceBot\node_modules\node-fetch\src\index.js from F:\Users\Basil Atif\Folders\VsauceBot\src\Commands\reddit.js not supported.
Instead change the require of index.js in F:\Users\Basil Atif\Folders\VsauceBot\src\Commands\reddit.js to a dynamic import() which is available in all CommonJS modules.    
  code: 'ERR_REQUIRE_ESM'

【问题讨论】:

你混淆了 import 和 require。动态导入是异步的,所以你命名的fetch 是一个promise 对象。 @jonrsharpe 好吧,我尝试使用 require() 并最终出错,在它说使用动态导入的错误中。我该怎么办? 您的上下文和原始错误不清楚。如果您使用的是动态导入,则 fetch 是 promise 解析 的内容。 @Baselistic 正确使用参见文档:npmjs.com/package/node-fetch#common-usage 仅供参考,您的个人信息似乎包含在底部错误堆栈跟踪的文件路径中。 【参考方案1】:

尝试使用这种导入方式:

import fetch from 'node-fetch';

【讨论】:

错误提示我不能在模块外使用导入。 尝试在你的 package.json 中添加“type”:“module” 造成了很多混乱,使用 require() 的所有内容现在都需要导入(很多),弹出一个新错误,说 .json 不是有效的文件扩展名,抱歉笨。 你能分享一下你的 package.json 吗? 您可以将 type="module" 添加到您想要使用的 javascript 文件中,而不是编辑 package.json,如下所示:<script type="module" src="main.js"></script>

以上是关于(已关闭)TypeError: fetch is not a function,我做错了啥?的主要内容,如果未能解决你的问题,请参考以下文章

急!急!微信小程序报错:TypeError: fetch is not a function

React + Fetch + Json。 TypeError:无法读取未定义的属性

TypeError: ‘float‘ object is not subscriptable 已解决

node-fetch "api key is not a legal HTTP header" 错误

TypeError: Object of type 'int32' is not JSON serializable ——已解决

已解决 - 未捕获的 TypeError: $(...).datetimepicker is not a function at app.js:61