从Fetch响应对象中获取文本

82

我使用 fetch 进行 API 调用,一切都能正常工作,但在这个特定的实例中,我遇到了一个问题,因为 API 返回的只是一个字符串,而不是一个对象。

通常情况下,API 返回一个对象,我可以解析 JSON 对象并获取想要的内容,但在这种情况下,我无法在响应对象中找到从 API 得到的文本。

响应对象的样子如下。 输入图像描述

我以为我会在 body 内找到文本,但我似乎找不到它。我该看哪里?


1
你可以使用 typeof 来检查返回的类型,如果是对象,则执行某些操作,如果是字符串,则执行其他操作。 - Mohd Asim Suhail
好的,但实际的文本响应在响应对象中在哪里?在 typeof 检查之后,我仍然需要从响应中提取我期望的字符串。 - Sam
使用 .text() 方法读取响应流。 - DAC84
3个回答

120

48

ES6 语法:

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

2
为什么会有两个then? - Timo
因为 response.text() 返回一个 Promise。 - Poul
2
虽然这个方法可行,但我建议使用 MDN 的模式(第二个 then 链接到 response.text())(来源)。 - thdoan
@thdoan,您介意解释一下为什么吗?难道不是同样的事情吗? - moeiscool

13

你可以用两种不同的方式实现这个功能:

  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>


9
2021年1月,response.text()的成功率为93.14%。 - Paul Rooney
你什么时候使用第二个选项? - Timo
2
% 使用率为何相关? - simPod
全局使用链接似乎已经失效,或者至少不再链接到有效/相关的内容。如果它们现在不相关,您能否修复它们或将其删除? - Drew Reese

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接