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

前端 未结 8 1727
滥情空心
滥情空心 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:44

    I was accidentally reusing a response object, something similar to this:

    const response = await new ReleasePresetStore().findAll();
    const json = await response.json();
    this.setState({ releasePresets: json });
    
    const response2 = await new ReleasePresetStore().findActive();
    const json2 = await response.json();
    this.setState({ active: json2 });
    console.log(json2);
    

    This line:

    const json2 = await response.json();
    

    Should have been (response2 instead of the used up response1):

    const json2 = await response2.json();
    

    Reusing the previous response made no sense and it was a dirty code typo...

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

    I also stuck into this. But this worked for me.

    fetch(YOUR_URL)
    .then(res => {
      try {
        if (res.ok) {
          return res.json()
        } else {
          throw new Error(res)
        }
      }
      catch (err) {
        console.log(err.message)
        return WHATEVER_YOU_WANT_TO_RETURN
      }
    })
    .then (resJson => {
      return resJson.data
    })
    .catch(err => console.log(err))
    

    good luck

    0 讨论(0)
提交回复
热议问题