Retrieve data from a ReadableStream object?(从 ReadableStream 对象中检索数据?)
问题描述
如何从 ReadableStream 对象获取信息?
How may I get information from a ReadableStream object?
我正在使用 Fetch API,但我没有从文档中看到这一点.
I am using the Fetch API and I don't see this to be clear from the documentation.
正文作为 ReadableStream 返回,我只想访问此流中的属性.在浏览器开发工具的响应下,我似乎将这些信息组织成属性,以 JavaScript 对象的形式.
The body is being returned as a ReadableStream and I would simply like to access a property within this stream. Under Response in the browser dev tools, I appear to have this information organised into properties, in the form of a JavaScript object.
fetch('http://192.168.5.6:2000/api/car', obj)
.then((res) => {
if(res.status == 200) {
console.log("Success :" + res.statusText); //works just fine
}
else if(res.status == 400) {
console.log(JSON.stringify(res.body.json()); //res.body is undefined.
}
return res.json();
})
推荐答案
为了从 ReadableStream 访问数据,您需要调用其中一种转换方法(可用文档 这里).
In order to access the data from a ReadableStream you need to call one of the conversion methods (docs available here).
举个例子:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function(response) {
// The response is a Response instance.
// You parse the data into a useable format using `.json()`
return response.json();
}).then(function(data) {
// `data` is the parsed version of the JSON returned from the above endpoint.
console.log(data); // { "userId": 1, "id": 1, "title": "...", "body": "..." }
});
如果您的数据返回类型不是 JSON,或者您不想要 JSON,请使用 text()
If your data return type is not JSON or you don't want JSON then use text()
举个例子:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function(response) {
return response.text();
}).then(function(data) {
console.log(data); // this will be a string
});
希望这有助于解决问题.
Hope this helps clear things up.
这篇关于从 ReadableStream 对象中检索数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 ReadableStream 对象中检索数据?
基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
