从JSON文件获取数据时出现问题

3

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

let transportation = [];


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

enter image description here


请查看控制台和/或网络选项卡。您收到了什么错误? - T.J. Crowder
我认为您需要检查路径是否正确,可以通过检查浏览器网络来确保。只需尝试路径../data/transportationDataCheck.json即可。 - user3766508
问题代码中有三个问题,但它们中没有一个可能是根本问题(尽管其中一个可能会指向根本问题):
  1. 您没有检查HTTP错误。这是“fetch” API中的一个陷阱(我在这里写过)。在第一个fulfillment处理程序中检查response.ok以查看HTTP请求是否成功(不幸的是,“fetch”仅在网络错误而不是HTTP错误时拒绝)。
  2. 没有理由使用最后两个fulfillment处理程序,只需使用一个即可。
  3. 您没有处理拒绝。
FWIW: https://pastebin.com/hPDUU25i
- T.J. Crowder
如果您直接尝试在URL中输入路径“APP_URL/data/transportationDataCheck.json”,会得到什么结果? - ROOT
3个回答

0

试试这个:

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

或者您可以尝试更改一下URL后再试一次

let transportation = [];


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

0
您正在尝试使用 fetch 命令提供静态文件,这要求文件本质上由服务器提供。
某人在此处遇到了类似的问题:Fetch request to local file not working 根据此文件的类型,您可能不需要进行 fetch。相反,您可以直接 require 该文件。
var transportationDataCheck = require('./data/transportationDataCheck.json');```

-1
使用路径开头处的 ./。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接