Lun*_*una 52 javascript fetch-api
当请求状态大于400(我已尝试过400,423,429状态)时,fetch无法读取返回的json内容.浏览器控制台中显示以下错误
未捕获(承诺)TypeError:无法在'Response'上执行'json':正文流被锁定
我显示了返回的响应对象的内容,如下所示:
但几个月前我仍然可以使用它.
我的问题如下:
PS:我的浏览器版本是Google Chrome 70.0.3538.102(正式版本)(64位)
Way*_*Wei 51
我也遇到了这个错误,但发现它与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
}
Run Code Online (Sandbox Code Playgroud)
因此,解决方案是避免Response.json()在then块中消耗多个。
Cri*_*ger 46
使用Response.clone()到克隆Response
例
fetch('yourfile.json').then(res=>res.clone().json())
Run Code Online (Sandbox Code Playgroud)
Bra*_*dia 11
'json'、'text' 之类的响应方法可以调用一次,然后锁定。发布的响应图像显示正文已锁定。这意味着您已经调用了“then”、“catch”。要重新喜欢它,您可以尝试以下操作。
fetch(url)
.then(response=> response.body.json())
.then(myJson=> console.log(myJson))
Run Code Online (Sandbox Code Playgroud)
或者
fetch(url)
.catch(response=> response.body.json())
.catch(myJson=> console.log(myJson))
Run Code Online (Sandbox Code Playgroud)
小智 8
我知道为时已晚,但它可以帮助某人:
let response = await fetch(targetUrl);
let data = await response.json();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30658 次 |
| 最近记录: |