为什么记录fetch()的结果会“破坏”它(“主体流被锁定”)?

时间:2019-01-07 21:45:48

标签: javascript fetch-api

在尝试了解返回结果时,我遇到了以下简单问题:

    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

那是为什么?

1 个答案:

答案 0 :(得分:6)

诺言并没有真正打破,但问题是.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));
相关问题