Why does logging the result of fetch() “break” it (“body stream is locked”)?

无人久伴 提交于 2019-12-10 16:00:02

问题


In trying to understand a return result, I ended up with this simple thing:

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

which works - it prints the json of the response.

But this does not work:

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

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

Why is that?


回答1:


The promise does not really break, but the problem is that .json() (and .body(), .text()) may only be called once.

The HTTP request is modeled as a stream, and you can't really read from a stream twice.

However, you can put the result of the .json() promise in a variable, and return that instead.

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


来源:https://stackoverflow.com/questions/54082327/why-does-logging-the-result-of-fetch-break-it-body-stream-is-locked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!