1

I'm trying to use node-fetch in order to fetch this website that has this JSON file where I can use it for my discord bot.

Code (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;
        }

It errors saying:

TypeError: fetch is not a function

How do I fix this?

FYI, Using require() resulted in an error as such:

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'
}
Baselistic
  • 57
  • 1
  • 1
  • 8
  • 2
    You're mixing up import and require. Dynamic import is _asynchronous_, so what you've named `fetch` is a promise object. – jonrsharpe Sep 27 '21 at 19:30
  • @jonrsharpe Well, I tried to use require() and it ended up erroring, in the error it said to use a dynamic import. What do I do? – Baselistic Sep 27 '21 at 19:32
  • Your context and original error aren't clear. If you're using dynamic import, fetch is what the promise _resolves_ to. – jonrsharpe Sep 27 '21 at 19:33
  • @Baselistic See the documentation for the correct use: https://www.npmjs.com/package/node-fetch#common-usage – Barmar Sep 27 '21 at 19:34
  • FYI it looks like your personal info is included in the file path in the error stack trace at the bottom. – zacran Sep 27 '21 at 19:37

2 Answers2

5

Try using this style of import:

import fetch from 'node-fetch';
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
orsisi
  • 169
  • 5
0

Error:

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

output: Error

Solution:

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

output: now the data is fetched

Alpha
  • 1,413
  • 3
  • 9
  • 23