您没有多次致电fetch。您将其称为 once,然后尝试多次读取响应正文。这就是为什么错误提示您在流已关闭时尝试读取正文 - 当您第一次完成读取时它已关闭。
如果您想使用两次数据,请将其存储在某个地方并使用两次。
let thisIsUrl = 'https://api.covid19api.com/summary';
let a = fetch(thisIsUrl)
a.then((data) => {
return data.json()
}).then((apidata) => {
// **************** Use it twice here
}).catch((error) => {
console.log(error)
})
如果您想再次获取它,因为它可能已更新,请再次致电fetch:
let thisIsUrl = 'https://api.covid19api.com/summary';
fetch(thisIsUrl)
.then((data) => {
return data.json();
}).then((apidata) => {
console.log(apidata);
return apidata;
}).catch((error) => {
console.log(error);
});
// Presumably this is later (in time), not immediately after the above
fetch(thisIsUrl)
.then((fetchdata) => {
return fetchdata.json();
}).then((readingData) => {
console.log(readingData);
}).catch((err) => {
console.log(err);
});
最后,这似乎不太可能,但如果您真的想获取一次并通过承诺链在多个地方使用该结果,请保留来自then 的承诺,而不是来自fetch 的承诺:
let thisIsUrl = 'https://api.covid19api.com/summary';
let a = fetch(thisIsUrl)
.then((data) => {
return data.json()
});
a.then((apidata) => {
// ***** Use it here
}).catch((error) => {
console.log(error)
})
a.then((readingData) => {
// ***** And then again here
}).catch((err) => {
console.log(err);
});
旁注:您的代码正在成为fetch API 中的猎物;我已经在this blog post 中写过它。 fetch 只拒绝它对 network 错误的承诺,而不是 HTTP 错误。您必须通过在响应对象上检查ok,在第一个履行处理程序中自己检查这些:
fetch("/your/resource")
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status); // Or better, use an Error subclass
}
return response.json();
})
// ...