【问题标题】:fetch is not defined when access another file访问另一个文件时未定义 fetch
【发布时间】:2021-06-19 18:27:09
【问题描述】:

我正在尝试使用 fetch 访问其他文件中的数据,但它一直返回

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);
    });

我正在查看这个fetch API,但它没有说明我们是否需要安装任何东西

【问题讨论】:

标签: javascript arrays fetch


【解决方案1】:

您可能正在使用node,其中fetch 未定义,它仅在默认情况下在浏览器中可用。您可以将其安装为npmnode-fetch

【讨论】:

    【解决方案2】:

    正如 Marcos 所说,如果您使用的是node,则 fetch 方法将不可用。而要使用它,你需要安装“node-fetch”包,然后导入使用它。

    使用“node-fetch”后,您会收到另一个错误" Only absolute URLs are supported",要解决此问题,您需要提供文件的完整 URL。

    示例代码如下:

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

    【讨论】:

      猜你喜欢
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多