ruese
ruese

Reputation: 69

Receive chunked response from server in frontend

I have a node.js/Express Backend API which returns its response with response.write(chunks) within a loop.

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()

If I curl the Backend API with a POST it returns the response in chunks, which is what I want it to do!

If I try to get the response via the Angular V19 webpage it appears that the response also is chunked, at least if I look at the network-timing enter image description here The image shows two calls to the API. The first call is the one with the chunked answer, the second call returns the response via response.send(content)

BUT: The following snippet only gives back one console.info(res) with the entire response

this.http.post<any>('https://example.com/posts', payload, 
{responseType: 'text' as 'json'}).subscribe({
    next: (res: any) => {
        console.info(res)
    },
    error: [...],
    done: [...]
})

Any ideas?

SOLUTION The comment from @Andrei gave me a valuable hint! The final solution

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: [...]
})

Upvotes: 1

Views: 41

Answers (0)

Related Questions