为什么记录fetch()的结果"打破"它("正文流被锁定")?

Gre*_*ade 4 javascript fetch-api

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

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

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

但这不起作用:

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

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

这是为什么?

Eve*_*ert 7

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

HTTP请求被建模为流,您无法真正从流中读取两次.

但是,您可以将.json()promise 的结果放在变量中,然后返回它.

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

  • Lightglobe :)令人放心的是,`.then(response => {let r = response.json(); console.log(r); return(r)})`做了我的预期.谢谢! (2认同)