简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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