从ReadableStream对象中检索数据? [英] Retrieve data from a ReadableStream object?
问题描述
我如何从ReadableStream对象获取信息?
我正在使用Fetch API,但我没有从文档中看到这一点。
正文作为ReadableStream返回,我只想访问此流中的属性。在浏览器开发工具的响应下,我似乎将这些信息以Javascript对象的形式组织到属性中。
fetch('http://192.168.5.6:2000/api/car',obj)
。然后((res)=> {
if(res.status == 200){
console.log(Success:+ res.statusText); //效果很好
}
else if(res.status == 400){
console.log(JSON.stringify(res.body.json()); // is.body is undefined。
}
返回res.json();
})
谢谢事先。
为了从 ReadableStream
访问数据您需要调用其中一种转换方法(文档可用此处例如:
fetch('https: //jsonplaceholder.typicode.com/posts/1')
.then(function(response){
//响应是响应实例。
//您将数据解析为au使用`.json()`
返回response.json();
})。then(function(data){
//`data`是从上面的端点返回的JSON的解析版本。
console.log(data); // { userId:1,id:1,title:...,body:...}
});
希望这有助于澄清问题。
How may I get information from a ReadableStream object?
I am using the Fetch API and I don't see this to be clear from the documentation.
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();
})
Thanks in advance.
In order to access the data from a ReadableStream
you need to call one of the conversion methods (docs available here).
As an example:
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": "..." }
});
Hope this helps clear things up.
这篇关于从ReadableStream对象中检索数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!