如何使用 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;
})
}
重要的是要记住这是异步的;readJson
返回之前this.users
有值;它稍后会得到它。如果你想知道它什么时候得到它,返回promise 以便调用代码可以then
在它上面使用:
readJson () {
// http://localhost:8080
return fetch('/Reading/api/file')
// ...
更多关于这些问题的答案:
如果您尝试/Reading/api/file
从文件系统中读取
...那么你不能,至少在某些浏览器中,除非你通过 web 服务器进程提供文件(因为你似乎正在提供页面。然后你通过该服务器进程上的 URL 读取它,如上所示。
要以其他方式读取本地文件,用户必须识别该文件,方法是input type="file"
将其选中或拖入拖放区。然后你会通过File API读取它,而不是fetch
.