javascript fetch - 无法在'Response'上执行'json':正文流被锁定

问题描述 投票:21回答:5

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

未捕获(承诺)TypeError:无法在'Response'上执行'json':正文流被锁定

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

enter image description here

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

我的问题如下:

  • 这只是Chrome浏览器的行为或获取标准的变化吗?
  • 有没有办法获得这些状态的身体内容?

PS: My browser version is Google Chrome 70.0.3538.102(正式版本) (64 位)

javascript fetch-api
5个回答
26
投票

我也遇到了这个错误,但发现它与Response的状态无关,真正的问题是你只能消耗Response.json()一次,如果你不止一次消耗它,那么错误就会发生。

如下:

    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

    }

25
投票

使用Response.clone()克隆Response

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

2
投票

响应方法如“json”,“text”可以调用一次,然后锁定。发布的响应图像显示正在锁定身体。这意味着你已经调用了'then','catch'。要重新开始,您可以尝试以下方法。

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

要么

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

1
投票

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

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);

这一行:

const json2 = await response.json();

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

const json2 = await response2.json();

重复使用之前的响应毫无意义,这是一个肮脏的代码错误...


0
投票

我也坚持这个。但这对我有用。

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))

祝好运

© www.soinside.com 2019 - 2024. All rights reserved.