我想在我的项目中多次调用这个 api,当我调用它时,它继续给出一个错误
类型错误:无法在“响应”上执行“json”:主体流已在 main.js 中读取:
Line number
我的代码如下
let thisIsUrl = 'https://api.covid19api.com/summary';
let a = fetch(thisIsUrl)
a.then((data) => {
return data.json()
}).then((apidata) => {
console.log(apidata)
return apidata
}).catch((error) => {
console.log(error)
})
a.then((fetchdata) => {
return fetchdata.json()
}).then((readingData) => {
console.log(readingData)
}).catch((err) => {
console.log(err)
})
你不会fetch
多次打电话。您调用它一次,然后尝试多次读取响应正文。这就是为什么当流已经关闭时错误说您正在尝试读取正文 - 当您第一次完成读取它时它已关闭。
如果要两次使用数据,请将其存储在某处并使用两次。
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);
});
最后,这似乎不太可能,但是如果您真的想获取一次并通过承诺链在多个地方使用该结果,请保留承诺 fromthen
而不是承诺 from 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中的猎物;我已经在这篇博文中写到了。fetch
只拒绝它对网络错误的承诺,而不是 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();
})
// ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句