为什么记录 fetch() "break" 的结果 ("body stream is locked")?
Why does logging the result of fetch() "break" it ("body stream is locked")?
在试图理解 return 结果时,我得到了这个简单的结果:
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
这是为什么?
承诺并没有真正失效,但问题是 .json()
(和 .body()
、.text()
)可能只被调用一次。
HTTP 请求被建模为流,您无法真正从流中读取两次。
但是,您可以将 .json()
promise 的结果放在变量中,而 return 则改为。
fetch('http://localhost:8081/position', {mode: 'cors'})
.then(response => response.json())
.then(jsonBody => { console.log(jsonBody); return jsonBody; })
.then(result => console.log(result));
在试图理解 return 结果时,我得到了这个简单的结果:
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
这是为什么?
承诺并没有真正失效,但问题是 .json()
(和 .body()
、.text()
)可能只被调用一次。
HTTP 请求被建模为流,您无法真正从流中读取两次。
但是,您可以将 .json()
promise 的结果放在变量中,而 return 则改为。
fetch('http://localhost:8081/position', {mode: 'cors'})
.then(response => response.json())
.then(jsonBody => { console.log(jsonBody); return jsonBody; })
.then(result => console.log(result));