最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - fetch is not defined when access another file - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 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.

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.

发布评论

评论列表(0)

  1. 暂无评论