Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why fetch Body object can be read only once?

The fetch specification states that the readable stream Body contains the Body.bodyUsed flag which is initially set to false and then is set to true with a call of any parsing method.

Here's an example:

fetch('/some/path', (res) => {
    // res.body.bodyUsed === false
    res.json();
    // res.body.bodyUsed === true
});

If you try to call a method like res.json() or res.text() once again, an exception is thrown.

The question is: why that behavior is used? Why not to allow parsing that readable stream as many times as one wants? I found no explanation of the matter.

PS. In Chrome (and maybe other browsers), that flag is accessible as res.body.locked.

like image 529
Phil Filippak Avatar asked Oct 14 '17 07:10

Phil Filippak


People also ask

Why is fetch better than Axios?

Without question, some developers prefer Axios over built-in APIs for its ease of use. But many overestimate the need for such a library. The fetch() API is perfectly capable of reproducing the key features of Axios, and it has the added advantage of being readily available in all modern browsers.

What type of object does a fetch call return?

The Response Object returned by a fetch() call contains all the information about the request and the response of the network request.


1 Answers

The question is: why that behavior is used? Why not to allow parsing that readable stream as many times as one wants?

It is possible to read Response.body more than once by using Response.clone()

like image 197
guest271314 Avatar answered Oct 17 '22 11:10

guest271314