Retrieve data from a ReadableStream object?
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 });
Hope this helps clear things up.
Some people may find an async
example useful:
var response = await fetch("https://httpbin.org/ip");var body = await response.json(); // .json() is asynchronous and therefore must be awaited
json()
converts the response's body from a ReadableStream
to a json object.
The await
statements must be wrapped in an async
function, however you can run await
statements directly in the console of Chrome (as of version 62).
res.json()
returns a promise. Try ...
res.json().then(body => console.log(body));