javascript fetch - Failed to execute 'json' on 'Response': body stream is locked

前端 未结 8 1752
滥情空心
滥情空心 2021-01-30 09:58

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 cons

8条回答
  •  死守一世寂寞
    2021-01-30 10:37

    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.

提交回复
热议问题