关于javascript fetch:javascript fetch-无法在“响应”上执行“ json”:主体流已锁定

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

当请求状态大于400(我尝试过400、423、429个状态)时,提取无法读取返回的json内容。 浏览器控制台中显示以下错误

Uncaught (in promise) TypeError: Failed to execute 'json' on
'Response': body stream is locked

我显示了返回的响应对象的内容,如下所示:

enter image description here

但是几个月前我仍然可以使用它。

我的问题如下:

  • 这仅仅是Chrome浏览器的行为还是获取标准的更改?
  • 有什么方法可以获取这些状态的身体含量吗?

PS:我的浏览器版本是Google Chrome 70.0.3538.102(正式版本)(64位)


我也遇到了这个错误,但是发现它与Response的状态无关,真正的问题是您只能消费一次Response.json(),如果多次消费Response.json(),则会发生错误。

如下所示:

1
2
3
4
5
6
7
    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

    }

因此,解决方案是避免在then块中多次使用Response.json()


使用Response.clone()克隆Response

1
fetch('yourfile.json').then(res=>res.clone().json())


像" json"," text"这样的响应方法可以被调用一次,然后锁定。
张贴的响应图像显示主体已锁定。
这意味着您已经称呼" then"," catch"。要对此重做,您可以尝试以下操作。

1
2
3
fetch(url)
    .then(response=> response.body.json())
    .then(myJson=> console.log(myJson))

要么

1
2
3
fetch(url)
    .catch(response=> response.body.json())
    .catch(myJson=> console.log(myJson))

我也坚持这一点。但这对我有用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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))

祝好运


我不小心重用了一个响应对象,类似于以下内容:

1
2
3
4
5
6
7
8
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);

这行:

1
const json2 = await response.json();

应该是(response2而不是用完的response1):

1
const json2 = await response2.json();

重用之前的响应没有任何意义,这是一个肮脏的代码错字...