如何在JavaScript中使用fetch()读取JSON文件?

时间:2018-08-15 13:08:28

标签: javascript json

如何使用javascript中的提取功能读取本地JSON文件? 我有带有一些转储数据的JSON文件和一个读取服务器上JSON文件的函数。 例如:

readJson () {
   console.log(this)
   let vm = this
   // http://localhost:8080
   fetch('/Reading/api/file').then((response) => response.json()).then(json => {
       vm.users = json
       console.log(vm.users)
   }).catch(function () {
       vm.dataError = true
   })
}

那么,在此提取函数中读取本地json文件必须做什么?

2 个答案:

答案 0 :(得分:6)

  

如何使用javascript中的提取功能读取本地JSON文件?

如果您想阅读http://localhost:8080/Reading/api/file

...那么您正在做的事情是正确的,只是您缺少.ok检查(这是我为此写的a blog post的常见错误)。另外,由于您使用的是箭头功能,因此除非您愿意使用let vm = this;,否则就不需要这样做。箭头功能关闭 this。所以:

readJson () {
   // http://localhost:8080
   fetch('/Reading/api/file')
   .then(response => {
       if (!response.ok) {
           throw new Error("HTTP error " + response.status);
       }
       return response.json();
   })
   .then(json => {
       this.users = json;
       //console.log(this.users);
   })
   .catch(function () {
       this.dataError = true;
   })
}

请务必记住,这是异步readJsonthis.users拥有值之前返回;它会以后。如果您想知道何时获得它,请返回承诺,以便调用代码可以在其上使用then

readJson () {
   // http://localhost:8080
   return fetch('/Reading/api/file')
   // ...

这些问题的答案更多:

如果您要尝试从文件系统读取/Reading/api/file

...那么,至少在某些浏览器中,您无法通过Web服务器进程提供文件(因为您似乎在为页面提供服务。然后,您通过该服务器进程上的URL读取该文件为:如上所示。

要以其他方式读取本地文件,用户必须通过在input type="file"中将其选中或将其拖动到放置区中来标识该文件。然后,您将通过File API而不是fetch来阅读它。

答案 1 :(得分:1)

有一个非常简单的Fetch API

您可以通过以下方式简单地使用它:

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