【问题标题】:Getting FastApi StreamedResponse via JS通过 JS 获取 FastApi StreamedResponse
【发布时间】:2021-12-08 15:45:31
【问题描述】:

我正在尝试使用 fetch 获取并控制台记录我通过 StreamedResponse 从 FastApi 流式传输的数据,但我无法使其正常工作。 Chrome 说Cannot read properties of null (reading 'getReader') 因为response.body 为空。我做错了什么?

服务器

async def foo():
    for i in range(5):
        time.sleep(1)
        yield b'foobar'

@app.get('/bar')
async def bar():
    return StreamingResponse(foo(), media_type='text/plain')

客户

async function buttonclick() {
        let url = 'http://localhost:8000/bar';

        let options = {
            mode: 'no-cors',
            method: 'GET'
        }

        fetch(url, options)
            .then(processChunkedResponse)
            .then(onChunkedResponseComplete)
            .catch(onChunkedResponseError);

    }


    function onChunkedResponseComplete(result) {
        console.log('all done!', result)
    }

    function onChunkedResponseError(err) {
        console.error(err)
    }

    function processChunkedResponse(response) {
        var text = '';
        var reader = response.body.getReader()
        var decoder = new TextDecoder();

        return readChunk();

        function readChunk() {
            return reader.read().then(appendChunks);
        }

        function appendChunks(result) {
            var chunk = decoder.decode(result.value || new Uint8Array, {stream: !result.done});
            console.log('got chunk of', chunk.length, 'bytes')
            text += chunk;
            console.log('text so far is', text.length, 'bytes\n');
            if (result.done) {
                console.log('returning')
                return text;
            } else {
                console.log('recursing')
                return readChunk();
            }
        }
    }

【问题讨论】:

    标签: javascript fetch streaming fastapi


    【解决方案1】:

    A no-cors Request.mode 返回一个不透明的响应和“JavaScript 可能无法访问结果响应的任何属性”。您的服务器可以提供标头Access-Control-Allow-Origin,客户端应该使用标准的cors fetch。

    此外,您可能需要进行此更改以确保返回 Promise:

    if (result.done) {
      //return text
      return Promise.resolve(text)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 2014-12-30
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多