【问题标题】:How to read JSON file with fetch() in javascript?如何在 javascript 中使用 fetch() 读取 JSON 文件?
【发布时间】:2018-08-15 13:08:28
【问题描述】:

如何在 javascript 中使用 fetch 函数读取本地 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
   })
}

那么,在这个 fetch 函数中读取本地 json 文件必须做什么?

【问题讨论】:

  • 旁注:您的fetch 呼叫缺少对response.ok 的检查;这是我写的一个常见错误a blog post about it

标签: javascript json


【解决方案1】:

如何在 javascript 中使用 fetch 函数读取本地 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 有值之前返回; 稍后会得到它。如果你想知道它什么时候得到它,return这个promise,这样调用代码就可以使用then了:

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

更多问题的答案:

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

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

若要读取本地文件,用户必须通过在input type="file" 中选择文件或将其拖入放置区来识别文件。然后你会通过File API而不是fetch阅读它。

【讨论】:

  • 这个例子使它看起来像是在http://localhost:8080/Reading/api/file 提供服务,所以我不确定这个答案是否适用。
  • @zzzzBov - 我完全错过了源中的评论,谢谢。但听起来 OP 可能在那里托管 page,但试图读取本地文件,而不是服务器上的文件。
  • 是的,这肯定是模棱两可的。我有一种预感,这是 "How do I return the response from an asynchronous call?" 的骗子。
  • @zzzzBov - 很可能。我已经确定了答案,再次感谢。
【解决方案2】:

还有很简单的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
});

【讨论】:

  • 他们在做什么,包括你错过了.ok 检查就像 OP 一样。
  • 他们不返回 respon.json();
  • 是的,他们有。他们正在使用concise arrow function。这有一个隐含的return
  • 我想在本地读取 json 文件,或者如果我必须准确地说,必须有一个属性说明 if property = true ,然后加载本地 json 文件(带有转储数据),否则加载 json 数据Tomcat服务器
  • 我通过明确将 url 形成为 localhost:3000/ 来做到这一点。成功了!
猜你喜欢
  • 2020-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多