簡體   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