'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

I got an error like text above. There is a problem in the code where i marked "<<<". Why isn't it working?



Solution 1:[1]

You can only read Response.text() once, if you want to console.log it, you can store it to a variable first.

By the way, res.text() returns a Promise. You will get the result of this Promise inside next .then.

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);
        });
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Coxxs