[英]uncaught type error while using fetch in javascript
function fetchPage(name){
fetch(name)
.then(res=>{
console.log(res);
console.log(res.text()); <<<
return res.text(); <<<
})
.then(text=>{
document.querySelector('article').innerHTML=text;
console.log(text);
});
}
Uncaught (in promise) TypeError: Failed to execute 'text' on 'Response': body stream already read at index.html:30:18
未捕获(承诺)类型错误:无法在“响应”上执行“文本”:正文 stream 已在索引处读取。html:30:18
I got an error like text above.我收到了类似上面文字的错误。 There is a problem in the code where i marked "<<<".
我标记为“<<<”的代码中存在问题。 Why isn't it working?
为什么它不起作用?
You can only read Response.text()
once, if you want to console.log
it, you can store it to a variable first.您只能读取
Response.text()
一次,如果要对其进行console.log
,可以先将其存储到变量中。
By the way, the res.text()
returns a Promise
.顺便说一句,
res.text()
返回一个Promise
。 You will get the result of this Promise inside next .then
.您将在 next
.then
中获得此 Promise 的结果。
function fetchPage(name) {
fetch(name)
.then(res => {
console.log(res);
let textPromise = res.text();
console.log(textPromise); // Promise
return textPromise;
})
.then(text => {
document.querySelector('article').innerHTML = text;
console.log(text);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.