首页 > 解决方案 > 为什么记录 fetch() 的结果会“破坏”它(“主体流被锁定”)?

问题描述

在试图理解返回结果时,我最终得到了这个简单的东西:

    fetch('http://localhost:8081/position', {mode: 'cors'})
        .then(response => {return response.json()})
        .then(result => console.log(result));

哪个有效 - 它打印响应的 json。

但这不起作用:

    fetch('http://localhost:8081/position', {mode: 'cors'})
        .then(response => {console.log(response.json()); return response.json();})
        .then(result => console.log(result));

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

这是为什么?

标签: javascriptfetch-api

解决方案


承诺并没有真正打破,但问题是.json()(and .body(), .text()) 只能被调用一次。

HTTP 请求被建模为流,您不能真正从流中读取两次。

但是,您可以将 Promise 的结果.json()放在一个变量中,然后将其返回。

fetch('http://localhost:8081/position', {mode: 'cors'})
    .then(response => response.json())
    .then(jsonBody => { console.log(jsonBody); return jsonBody; })
    .then(result => console.log(result));

推荐阅读