【发布时间】: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