Getting Text From Fetch Response Object
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.
I thought I'd find the text inside the body but I can't seem to find it. Where do I look?
Solution 1:
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:
ES6 Syntax:
fetch("URL")
.then(response => response.text())
.then((response) => {
console.log(response)
})
.catch(err => console.log(err))
Solution 3:
You can do this in two different ways:
-
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>
-
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>