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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With