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

前端 未结 8 1726
滥情空心
滥情空心 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.

    0 讨论(0)
  • 2021-01-30 10:37

    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))
    
    0 讨论(0)
  • 2021-01-30 10:38

    This worked for me

    response.json().then(data => {
      // use data
    })
    
    0 讨论(0)
  • 2021-01-30 10:38

    As mentioned in the question when you're trying to use same response object, your body is about to locked due to state of the object. What you can do is that capture the value of the response object and then try to have some operation on it (.then()). Please follow the code below,

    fetch('someurl').then(respose) => {
        let somedata = response.json(); // as you will capture the json response, body will not be locked anymore. 
        somedata.then(data) => {
            {
                 error handling (if (data.err) { ---- })
            }
            {
                 operations (else { ---- })
            }
        } 
    }
    
    0 讨论(0)
  • 2021-01-30 10:39

    I know it's too late but it can help someone:

    let response = await fetch(targetUrl);
    let data = await response.json();
    
    0 讨论(0)
  • 2021-01-30 10:44

    Use Response.clone() to clone Response

    example

    fetch('yourfile.json').then(res=>res.clone().json())
    
    0 讨论(0)
提交回复
热议问题