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.
JavaScript
x
11
11
1
fetch('http://192.168.5.6:2000/api/car', obj)
2
.then((res) => {
3
if(!res.ok) {
4
console.log("Failure:" + res.statusText);
5
throw new Error('HTTP ' + res.status);
6
} else {
7
console.log("Success :" + res.statusText);
8
return res.body // what gives?
9
}
10
})
11
Advertisement
Answer
In order to access the data from a ReadableStream
you need to call one of the conversion methods (docs available here).
As an example:
JavaScript
1
10
10
1
fetch('https://jsonplaceholder.typicode.com/posts/1')
2
.then(function(response) {
3
// The response is a Response instance.
4
// You parse the data into a useable format using `.json()`
5
return response.json();
6
}).then(function(data) {
7
// `data` is the parsed version of the JSON returned from the above endpoint.
8
console.log(data); // { "userId": 1, "id": 1, "title": "...", "body": "..." }
9
});
10
EDIT: If your data return type is not JSON or you don’t want JSON then use text()
As an example:
JavaScript
1
7
1
fetch('https://jsonplaceholder.typicode.com/posts/1')
2
.then(function(response) {
3
return response.text();
4
}).then(function(data) {
5
console.log(data); // this will be a string
6
});
7