【问题标题】:problem when try to fetch data from json file尝试从 json 文件中获取数据时出现问题
【发布时间】:2020-07-02 08:39:29
【问题描述】:

我在尝试获取数据时遇到了一些问题,我没有得到响应。 我写的路径正确吗? 我附上了我的项目层次结构的部分代码和图片。

let transportation = [];


const init = () => {
  fetch('/data/transportationDataCheck.json')
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      transportation = data;
    }).then(() => {
      renderList(transportation);
    });
};

【问题讨论】:

  • 查看控制台和/或网络选项卡。你得到什么错误?
  • 我认为你需要检查路径是否正确。确保检查浏览器网络。只需尝试使用路径 ../data/transportationDataCheck.json
  • 问题中的代码存在三个问题,但它们都不是根本问题(尽管其中一个可能已经指出了根本问题): 1. 你是不检查 HTTP 错误。这是fetch API 中的一支足球枪(我在 [这里]() 写过它)。在您的第一个履行处理程序中检查 response.ok 以查看 HTTP 请求是否有效(遗憾的是,fetch 仅拒绝 network 错误,而不是 HTTP 错误)。 2. 没有理由使用最后两个履行处理程序,只需使用一个。 3. 你没有处理拒绝。 FWIW:pastebin.com/hPDUU25i
  • 如果你直接尝试URL中的路径APP_URL/data/transportationDataCheck.json会得到什么?

标签: javascript html json fetch


【解决方案1】:

试试这个:

const data = require("../data/transportationDataCheck.json")
console.log(JSON.stringify(data));

或者你可以换个小网址试试

let transportation = [];


const init = () => {
  fetch('../data/transportationDataCheck.json')
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      transportation = data;
    }).then(() => {
      renderList(transportation);
    });
};

【讨论】:

    【解决方案2】:

    在路径的开头使用 ./

    fetch('./data/transportationDataCheck.json')
    .then(response => {
      return response.json()
    })
    .then(data => {
      // Work with JSON data here
      console.log(data)
    })
    .catch(err => {
      // Do something for an error here
    })

    【讨论】:

      【解决方案3】:

      您正在尝试使用 fetch 命令提供静态文件,这本质上要求文件由服务器提供。

      这里有人遇到了类似的问题:Fetch request to local file not working

      根据这是什么类型的文件,您可能不需要进行提取。您可能需要该文件:

      var transportationDataCheck = require('./data/transportationDataCheck.json');```
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-16
        • 2014-05-26
        • 2020-03-02
        • 1970-01-01
        • 2018-02-17
        • 2021-11-26
        相关资源
        最近更新 更多