When the request status is greater than 400(I have tried 400, 423, 429 states), fetch cannot read the returned json content. The following error is displayed in the browser console
Uncaught (in promise) TypeError: Failed to execute 'json' on 'Response': body stream is locked
I showed the contents of the returned response object as follows:
But I can still use it a few months ago.
My question is as follows:
PS: My browser version is Google Chrome 70.0.3538.102(正式版本) (64 位)
I met this error too but found out it is not related to the state of Response, the real problem is that you only can consume Response.json() once, if you are consuming it more than once, the error will happen.
like below:
fetch('http://localhost:3000/movies').then(response =>{
console.log(response);
if(response.ok){
console.log(response.json()); //first consume it in console.log
return response.json(); //then consume it again, the error happens
}
So the solution is to avoid consuming Response.json() more than once in then block.
According to MDN, you should use Response.clone():
The
clone()method of theResponseinterface creates a clone of a response object, identical in every way, but stored in a different variable. The main reasonclone()exists is to allow multiple uses ofBodyobjects (when they are one-use only.)
Example:
fetch('yourfile.json').then(res=>res.clone().json())
Response methode like 'json', 'text' can be called once, and then it locks. The posted image of response shows that body is locked. This means you have already called the 'then', 'catch'. To reslove this you can try the following.
fetch(url)
.then(response=> response.body.json())
.then(myJson=> console.log(myJson))
Or
fetch(url)
.catch(response=> response.body.json())
.catch(myJson=> console.log(myJson))