Getting Text From Fetch Response Object

回眸只為那壹抹淺笑 提交于 2020-01-03 07:00:48

问题


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?


回答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 fetch docs: here




回答2:


ES6 Syntax :

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



回答3:


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>


来源:https://stackoverflow.com/questions/41946457/getting-text-from-fetch-response-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!