从ReadableStream对象中检索数据? [英] Retrieve data from a ReadableStream object?

查看:888
本文介绍了从ReadableStream对象中检索数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆