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

BRR*_*sev 6 javascript json

如何在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
   })
}
Run Code Online (Sandbox Code Playgroud)

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

T.J*_*der 7

如何在javascript中使用fetch函数读取本地JSON文件?

如果你想读书 http://localhost:8080/Reading/api/file

...然后你正在做的是正确的,除非你错过了.ok支票(这是一个常见的错误,我写了一篇关于它的博客文章).另外,既然你正在使用箭头功能,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;
   })
}
Run Code Online (Sandbox Code Playgroud)

重要的是要记住这是异步的 ; readJson返回之前this.users有值; 它会在以后得到它.如果你想知道它何时获得它,请返回 promise,以便调用代码可以使用then它:

readJson () {
   // http://localhost:8080
   return fetch('/Reading/api/file')
   // ...
Run Code Online (Sandbox Code Playgroud)

更多关于这些问题的答案:

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

...至少在某些浏览器中,除非您通过Web服务器进程提供服务(因为您似乎正在为页面提供服务),否则您不能通过该服务器进程上的URL读取它,如上所示.

要读取本地文件,用户必须通过在文件中选择文件input type="file"或将文件拖放到dropzone中来识别文件.然后你通过File API读取它,而不是fetch.


Bar*_*r J 7

有一个非常简单的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
});
Run Code Online (Sandbox Code Playgroud)

  • 是的,他们这样做。他们正在使用 [**简洁** 箭头函数](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)。那有一个隐含的`return`。 (3认同)
  • 这就是他们正在做的事情,包括你错过了“.ok”检查,就像OP一样。 (2认同)