Javascript 从获取响应对象获取文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41946457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:45:45  来源:igfitidea点击:

Getting Text From Fetch Response Object

javascriptajaxfetch

提问by Sam

I'm using fetchto 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.

我正在使用fetchAPI 调用,一切正常,但在这个特定实例中,我遇到了一个问题,因为 API 只返回一个字符串——而不是一个对象。

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.

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

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?

我以为我会在正文中找到文本,但似乎找不到。我在哪里看?

回答by Zach Tuttle

using the fetch javascript API you can try:

使用 fetch javascript API,您可以尝试:

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

also take a look at the fetch docs: here

也看看获取文档:here

回答by Mawardy

ES6 Syntax :

ES6 语法:

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

回答by Rosberg Linhares

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.bodyproperty 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>

  1. 第一个选项是使用该response.text()方法,但请注意,在 2019 年 12 月,其全球使用率仅为 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. 第二种选择是改用该response.body属性,这需要做更多的工作,但占全局使用率的 73.94%

    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>