2016-11-02 70 views
23

如何从ReadableStream对象获取信息?从ReadableStream对象中检索数据?

我正在使用Fetch API,但我没有看到从文档中明确这一点。

正在作为ReadableStream返回,我只想访问此流中的属性。在浏览器开发工具的响应下,我似乎将这些信息以Javascript对象的形式组织到属性中。

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(); 
    }) 

在此先感谢。

+1

[Body API参考](https://developer.mozilla.org/en-US/docs/Web/API/Body) –

+0

@FrancescoPezzella感谢您的回复。我尝试过'response.Body.json()',但我越来越_italic_ TypeError:无法读取未定义_italic_的属性'json'。 这是因为bodyUsed属性也设置为false? 但是,我可以在浏览器开发人员工具的响应选项卡下查看此主体。有一个我想要检索的错误消息。 – noob

+0

因此,您的问题纯粹与错误400条件有关?如果将处理程序更改为'console.log(res.json());会发生什么?你看到你期待的数据吗? –

回答

35

为了访问ReadableStream中的数据,您需要调用其中一种转换方法(文档可用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": "..." } 
    }); 

希望这有助于清楚的事情了。

+0

感谢您的回复。我已经尝试过这一点,并且仍然遇到res.body未定义的错误。我可以通过res.status在first()函数中检索状态。看来只有body是一个ReadableStream对象。它似乎锁定了一个属性,该属性设置为true? – noob

+0

你在哪里试图访问'res.body'(这不是我的例子的一部分)?你可以在你的原始问题中分享一些示例代码,以便在问题出现的地方更清楚地说明问题。 –

+0

我试着从第一个.then()函数返回的json响应中访问res.body。为了更加清晰,我在原始问题中添加了一个示例。谢谢! – noob

9

res.json()返回承诺。试试...

res.json().then(body => console.log(body)); 
+1

我试过了,打印出Promise而不是正文。 – reectrix

10

有些人可能会发现一个async例如有用:

var response = await fetch("https://httpbin.org/ip"); 
var body = await response.json(); // .json() is asynchronous and therefore must be awaited 

json()响应的身体从ReadableStream转换成JSON对象。

await语句必须封装在async函数中,但是您可以直接在Chrome的控制台(从版本62开始)运行await语句。

+4

非常适合在控制台提示符下进行试验。减少打字。 – Amitabh