Getting Text From Fetch Response Object

JavascriptAjaxFetch Api

Javascript Problem Overview


I'm using fetch to make API calls and everything works but in this particular instance I'm running into an issue because the API simply returns a string -- not an object.

Typically, the API returns an object and I can parse the JSON object and get what I want but in this case, I'm having trouble finding the text I'm getting from the API in the response object.

Here's what the response object looks like. enter image description here

I thought I'd find the text inside the body but I can't seem to find it. Where do I look?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

ES6 Syntax:

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

Solution 3 - Javascript

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamView Question on Stackoverflow
Solution 1 - JavascriptZach TuttleView Answer on Stackoverflow
Solution 2 - JavascriptMawardyView Answer on Stackoverflow
Solution 3 - JavascriptRosberg LinharesView Answer on Stackoverflow