NodeJS TypeError:fetch不是一个函数,我做错了什么?

ehxuflar  于 5个月前  发布在  Node.js
关注(0)|答案(2)|浏览(64)

我试图使用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'
}

mf98qq94

mf98qq941#

尝试使用此导入样式:

import fetch from 'node-fetch';

字符串

gfttwv5a

gfttwv5a2#

错误:

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()

字符串

输出:Error
解决方案:

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()

输出:now the data is fetched

相关问题