首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >(关闭) TypeError: fetch不是一个函数,我做错了什么?

(关闭) TypeError: fetch不是一个函数,我做错了什么?
EN

Stack Overflow用户
提问于 2021-09-27 19:26:33
回答 2查看 8.1K关注 0票数 0

我试图使用node-fetch来获取这个包含这个JSON文件的网站,在那里我可以将它用于我的异议机器人。

法典(JS):

代码语言:javascript
运行
复制
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;
        }

它错误地说:

代码语言:javascript
运行
复制
TypeError: fetch is not a function

我该怎么解决这个问题?

FYI使用require()会导致这样的错误:

代码语言:javascript
运行
复制
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'
}
EN

回答 2

Stack Overflow用户

发布于 2021-09-27 19:33:08

尝试使用这种类型的导入:

代码语言:javascript
运行
复制
import fetch from 'node-fetch';
票数 4
EN

Stack Overflow用户

发布于 2022-11-15 08:41:42

错误:

代码语言:javascript
运行
复制
let get=document.getElementById("get");
let **fetch**=document.getElementById("fetch"); //this var create problem
let content=document.getElementById("content");


function getData(){

    
    let url= "https://api.github.com/users/github";
    fetch(url).then(
        (res)=>{
        return res.text();
    }).then((data)=>{
    content.innerHTML = data;
    });

}
getData()

输出: 错误

解决方案:

代码语言:javascript
运行
复制
let get=document.getElementById("get");
let **fet**=document.getElementById("fetch");// change the name of the variable
let content=document.getElementById("content");


function getData(){

    
    let url= "https://api.github.com/users/github";
    fetch(url).then(
        (res)=>{
        return res.text();
    }).then((data)=>{
    content.innerHTML = data;
    });

}
getData()

输出: 现在数据被取了

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69352254

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档