FastAPI StreamingResponse无法返回流,浏览器报TypeError错误
问题解决:FastAPI StreamingResponse前端报错TypeError: stream.on is not a function
问题原因
浏览器环境中,axios设置responseType: "stream"并不会返回Node.js风格的Stream对象,而是返回浏览器原生的ReadableStream,它没有.on()方法,这就是报错的根本原因。
解决方案
方案1:修改axios的流式处理逻辑
直接使用浏览器ReadableStream的API来读取数据:
const response = await axios.get("http://localhost:8000/stream", { responseType: "stream", }); const reader = response.data.getReader(); const decoder = new TextDecoder('utf-8'); async function readStream() { const { done, value } = await reader.read(); if (done) { console.log('流已结束'); return; } // 解码并处理数据 console.log(decoder.decode(value, { stream: true })); readStream(); } readStream();
方案2:改用fetch(推荐,原生支持流式响应)
fetch在浏览器中对流式响应的支持更直观:
const response = await fetch("http://localhost:8000/stream"); const reader = response.body.getReader(); const decoder = new TextDecoder('utf-8'); async function readStream() { const { done, value } = await reader.read(); if (done) { console.log('流已结束'); return; } console.log(decoder.decode(value, { stream: true })); readStream(); } readStream();
额外注意事项
- 后端代码无需修改,你的
StreamingResponse实现是正确的,但如果前端和后端存在跨域问题,需要在FastAPI中配置CORS:
from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], # 生产环境请替换为具体前端域名 allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
- 无需添加
--h11-max-incomplete-event-size 0参数,该参数针对的是服务器端的请求大小限制,和当前前端报错无关。
内容的提问来源于stack exchange,提问作者anthnyprschka
相关产品推荐
相关产品推荐

