Stream API – Response Body


Stream API – Response Body



”;


In Stream API, the body is a property of the Response interface. It is used to get the body content of ReableStream. It is a read-only property. The response body is not sent in a single body but it sends in small chunks and the client starts processing as soon as it receives data. It does not have to wait till the complete response.

Syntax


Response.body

This property return either ReadableStream or null for any Response object which is created with null body property.

Example

In the following program, we will see how to use Response Body in Stream API. So for that, we send a GET request using fetch() to the given URL. If the response is successful, then using the response body is obtained as a “ReadableStream” with the help of response.body.getReader(). Then we define a readMyStream() function to read the data chunks received from the stream. If any error occurs, then it is successfully handled by the catch() function.


<script>
   // fetch() function to send GET request 
   fetch(''http://example.com/'')
   .then(response => {
      if (response.ok) {
      // Using body property we get the ReadableStream 
      const myReader = response.body.getReader();
   
      // Using this function we read the chunks 
      function readMyStream() {
         return myReader.read().then(({ done, value }) => {
            if (done) {
               // Stream is completed
               return;
            }
            // Process the data from the chunks 
            const receivedData = new TextDecoder().decode(value);
            console.log(receivedData);
   
            // Continue reading 
            return readMyStream();
         });
      }
      return readMyStream();
      } 
   })
   .catch(error => {
      // Handling error
      console.log(''Found Error:'', error);
   });
</script>

Conclusion

So this is how the Response Body body works. Before using the Response body always check if the specified API supports streaming responses or not. Because not all the APIs support streaming responses. Now in the next article, we will learn about byte readers in Stream API.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *