Search code examples
javascriptfetch-api

Retrieve data from a ReadableStream object?


How may I get information from a ReadableStream object?

I am using the Fetch API and I don't see this to be clear from the documentation.

The body is being returned as a ReadableStream and I would simply like to access a property within this stream. Under Response in the browser dev tools, I appear to have this information organised into properties, in the form of a JavaScript object.

fetch('http://192.168.5.6:2000/api/car', obj)
    .then((res) => {
        if(!res.ok) {
            console.log("Failure:" + res.statusText);
            throw new Error('HTTP ' + res.status);
        } else {
            console.log("Success :" + res.statusText);
            return res.body // what gives?
        }
    })

Solution

  • In order to access the data from a ReadableStream you need to call one of the conversion methods (docs available here).

    As an example:

    fetch('https://jsonplaceholder.typicode.com/posts/1')
      .then(function(response) {
        // The response is a Response instance.
        // You parse the data into a useable format using `.json()`
        return response.json();
      }).then(function(data) {
        // `data` is the parsed version of the JSON returned from the above endpoint.
        console.log(data);  // { "userId": 1, "id": 1, "title": "...", "body": "..." }
      });
    

    EDIT: If your data return type is not JSON or you don't want JSON then use text()

    As an example:

    fetch('https://jsonplaceholder.typicode.com/posts/1')
      .then(function(response) {
        return response.text();
      }).then(function(data) {
        console.log(data); // this will be a string
      });