Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does logging the result of fetch() "break" it ("body stream is locked")?

In trying to understand a return result, I ended up with this simple thing:

    fetch('http://localhost:8081/position', {mode: 'cors'})
        .then(response => {return response.json()})
        .then(result => console.log(result));

which works - it prints the json of the response.

But this does not work:

    fetch('http://localhost:8081/position', {mode: 'cors'})
        .then(response => {console.log(response.json()); return response.json();})
        .then(result => console.log(result));

It thows Uncaught (in promise) TypeError: Failed to execute 'json' on 'Response': body stream is locked

Why is that?

like image 970
GreenAsJade Avatar asked Dec 23 '22 01:12

GreenAsJade


1 Answers

The promise does not really break, but the problem is that .json() (and .body(), .text()) may only be called once.

The HTTP request is modeled as a stream, and you can't really read from a stream twice.

However, you can put the result of the .json() promise in a variable, and return that instead.

fetch('http://localhost:8081/position', {mode: 'cors'})
    .then(response => response.json())
    .then(jsonBody => { console.log(jsonBody); return jsonBody; })
    .then(result => console.log(result));
like image 115
Evert Avatar answered May 19 '23 09:05

Evert