2

I' trying to use fetch to access data in other file but it keeps return

ReferenceError: fetch is not defined
      const getData = async () => {
      const fetchedData = await fetch("./dino.json");
      const data = await fetchedData.json();
      return data.Dinos;
    };
    getData().then(data => {
      console.log(data); // will print the array
    }).catch(error => {
      console.error(error);
    });

I am looking at this fetch API but it did not specify that if we need install anything

Tony Li
  • 31
  • 1
  • 1
  • 4
  • Does this answer your question? [ReferenceError: fetch is not defined](https://stackoverflow.com/questions/48433783/referenceerror-fetch-is-not-defined) – Phoenix Mar 23 '21 at 04:52

4 Answers4

3

You are probably using node where fetch is not defined, it's only available by default in a browser. U can install it as a npm package node-fetch.

marcos
  • 4,473
  • 1
  • 10
  • 24
0

As Marcos said, If you are using a node, the fetch method will not be available. And to use it, you need to install the "node-fetch" package and then import to use it.

After using "node-fetch", you'll get another error " Only absolute URLs are supported", to fix that, you need to give the full URL of the file.

Here is the example code:

import fetch from 'node-fetch' 

const getData = async () => {
      const fetchedData = await fetch("http://localhost:3000/dino.json");
      const data = await fetchedData.json();
      return data.Dinos;
    };
Riyaz Khan
  • 2,765
  • 2
  • 15
  • 29
0

If you upgrade from Node.js 18 or higher, you won't get the error anymore. The versions include an experimental globally available Fetch API. See the Node.js documentation for more details.

Stanley Ulili
  • 702
  • 5
  • 7
0

Sometimes this happens because you are using a node version older than 18 which doesn't include "fetch".

You can either install the dependency as stated in other responses or update your node version.

Franco Petra
  • 688
  • 7
  • 18