Getting Text From Fetch Response Object

Using the fetch JavaScript API you can try:

response.text().then(function (text) {
  // do something with the text response 
});

Also take a look at the docs on fetch > response > body interface methods


You can do this in two different ways:

  1. The first option is to use the response.text() method, but be aware that, at Dec/2019, its global usage is only 36.71%:

    async function fetchTest() {
        let response = await fetch('https://httpbin.org/encoding/utf8');
        let responseText = await response.text();
    
        document.getElementById('result').innerHTML = responseText;
    }
    
    (async() => {
        await fetchTest();
    })();
    <div id="result"></div>
  2. The second option is to use the response.body property instead, which requires a little more work but has 73.94% of global usage:

    async function fetchTest() {
        let response = await fetch('https://httpbin.org/encoding/utf8');
        let responseText = await getTextFromStream(response.body);
        
        document.getElementById('result').innerHTML = responseText;
    }
    
    async function getTextFromStream(readableStream) {
        let reader = readableStream.getReader();
        let utf8Decoder = new TextDecoder();
        let nextChunk;
        
        let resultStr = '';
        
        while (!(nextChunk = await reader.read()).done) {
            let partialData = nextChunk.value;
            resultStr += utf8Decoder.decode(partialData);
        }
        
        return resultStr;
    }
    
    (async() => {
        await fetchTest();
    })();
    <div id="result"></div>

ES6 Syntax:

fetch("URL")
   .then(response => response.text())
   .then((response) => {
       console.log(response)
   })
   .catch(err => console.log(err))