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
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
Share Improve this question asked Mar 23, 2021 at 4:46 Tony LiTony Li 311 gold badge1 silver badge4 bronze badges 1- Does this answer your question? ReferenceError: fetch is not defined – Phoenix Commented Mar 23, 2021 at 4:52
4 Answers
Reset to default 3You 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.
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;
};
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.
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.