如何基于RTK Query处理Node流?
在RTK Query中处理Node纯文本流
端点配置
在RTK Query的mutation端点中,通过自定义responseHandler直接返回响应体(原始ReadableStream),跳过默认的JSON解析逻辑:
teamSkillsActionableInsights: builder.mutation<Response, TeamSkillsReport>({ query: (teamSkillsReportData) => ({ url: "reports/team/skills/actionable-insights", method: "POST", body: teamSkillsReportData, responseHandler: async (response) => response.body, }), })
前端消费流数据
调用mutation获取流后,通过ReadableStream.getReader()逐块读取数据,结合TextDecoder解码为文本并实时更新状态:
const [aiActionableInsights, setAiActionableInsights] = useState(""); const [updatePost] = useTeamSkillsActionableInsightsMutation(); const getUserSkillsActionableInsights = async () => { const response = await updatePost(teamSkillsReportData).unwrap(); let total = ""; const reader = response?.getReader(); const decoder = new TextDecoder("utf-8"); while (true) { const { done, value: chunk } = await reader.read(); if (done) break; const decodedValue = decoder.decode(chunk); total += decodedValue; setAiActionableInsights(total); } };
关键注意事项
- 服务器必须返回
text/plain; charset=utf-8响应头,保证流数据格式匹配解码逻辑 responseHandler返回response.body是核心:这一步是让RTK Query放弃默认的JSON解析,保留原始流对象供后续处理- 逐块解码拼接后更新状态,可实现文本内容的流式展示效果
内容的提问来源于stack exchange,提问作者Mojtaba
相关产品推荐
相关产品推荐

