Angular 19如何接收Node.js/Express后端的分块响应?
问题:Angular无法接收Express分块响应,仅获取完整内容
我有一个Node.js/Express后端API,通过循环调用response.write(chunks)返回分块响应,代码如下:
res.setHeader('Content-Type', 'text/plain; charset=utf-8'); res.setHeader('Transfer-Encoding', 'chunked'); for await (const part of response) { res.write(part.message.content) } res.end()
使用curl发起POST请求调用该API时,能正常获取分块响应,符合预期。
但通过Angular 19网页调用该API时,尽管网络时序显示响应是分块的(两次API调用对比:第一次是分块响应,第二次通过response.send(content)返回完整响应),但以下代码仅能在console.info(res)中得到完整响应,无法逐块接收内容:
this.http.post<any>('https://example.com/posts', payload, {responseType: 'text' as 'json'}).subscribe({ next: (res: any) => { console.info(res) }, error: [...], done: [...] })
解决方案
感谢@Andrei的提示,最终解决代码如下:
this.http.post<any>('https://example.com/posts', payload, { observe: 'events', reportProgress: true, responseType: 'text' as 'json' }).subscribe({ next: (event: any) => { if (event.type === HttpEventType.DownloadProgress) { console.info(event.partialText) } }, error: [...], done: [...] })
关键说明:
- 设置
observe: 'events',让Angular HttpClient监听所有HTTP事件,而非仅返回最终的完整响应 - 开启
reportProgress: true,启用进度事件的报告机制 - 在订阅的
next回调中,判断事件类型为HttpEventType.DownloadProgress,通过event.partialText获取每一块的响应内容
内容的提问来源于stack exchange,提问作者ruese
相关产品推荐
相关产品推荐

