繁体   English   中英

在 javascript 中使用 fetch 时出现未捕获的类型错误

[英]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);
});
}

未捕获(承诺)类型错误:无法在“响应”上执行“文本”:正文 stream 已在索引处读取。html:30:18

我收到了类似上面文字的错误。 我标记为“<<<”的代码中存在问题。 为什么它不起作用?

您只能读取Response.text()一次,如果要对其进行console.log ,可以先将其存储到变量中。

顺便说一句, res.text()返回一个Promise 您将在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM