javascript - 为什么记录 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
这是为什么?
解决方案
承诺并没有真正打破,但问题是.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));
推荐阅读
- c++ - SIGSEGV,分段错误。while printf() 数组索引的值
- javascript - 使用 D3/JavaScript 更改所选 li 选项的颜色
- php - 获取mysql中的多条记录并存入json数组中显示在HTML表格单单字段中
- console - 将用户的配置文件加载到 symfony 控制台
- reactjs - REACT - 组件与 TypeScript 中的子组件的组合
- javascript - 是否有可能使用 JS 获得 HTML 文本单词(或单词)的像素完美尺寸
- javascript - 如何使用 JavaScript/Jquery 在浏览器关闭选项卡上显示带有自定义 HTML 的弹出窗口?我有自定义 HTML 弹出窗口
- tsql - SQL 表中的重复姓氏
- sql - BCP 实用程序:无法导出到具有空值的文本文件
- spring-boot - 当 eureka 服务器重新启动时,客户端无法重新注册到 eureka 服务器