从ReadableStream对象中检索数据?

时间:2016-11-02 16:35:25

标签: javascript node.js reactjs fetch

我如何从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();
    })  

提前致谢。

8 个答案:

答案 0 :(得分:82)

要从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": "..." }
  });

希望这有助于清理事情。

答案 1 :(得分:24)

有些人可能会发现var response = await fetch("https://httpbin.org/ip"); var body = await response.json(); // .json() is asynchronous and therefore must be awaited 示例很有用:

json()

ReadableStream将响应的正文从await转换为json对象。

async语句必须包含在await函数中,但您可以直接在Chrome控制台中运行public class ViewModel() { public CustomerInfo info {get; set;} public int id {get; set;} } 语句(自版本62起)。

答案 2 :(得分:21)

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

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

答案 3 :(得分:10)

参加派对有点晚了,但是从使用Sharepoint Framework的Odata $批量请求生成的ReadableStream中获取一些有用的东西时遇到了一些问题。

与OP有类似的问题,但我的解决方案是使用与.json()不同的转换方法。在我的情况下.text()就像一个魅力。但是,为了从文本文件中获取一些有用的JSON,必须进行一些调整。

答案 4 :(得分:4)

如果您只想将响应作为文本,并且不想将其转换为JSON,请使用https://developer.mozilla.org/en-US/docs/Web/API/Body/text,然后使用then来获得承诺的实际结果:

fetch('city-market.md')
  .then(function(response) {
    response.text().then((s) => console.log(s));
  });

fetch('city-market.md')
  .then(function(response) {
    return response.text();
  })
  .then(function(myText) {
    console.log(myText);
  });

答案 5 :(得分:3)

请注意,您只能读取一次流,因此在某些情况下,您可能需要克隆响应才能重复读取它:

fetch('example.json')
  .then(res=>res.clone().json())
  .then( json => console.log(json))

fetch('url_that_returns_text')
  .then(res=>res.clone().text())
  .then( text => console.log(text))

答案 6 :(得分:2)

我不喜欢那时的连锁。然后,第二个将无法访问状态。如前所述,“ response.json()”返回一个承诺。在类似于第二秒的行为中返回“ response.json()”的当时结果。它具有响应范围的额外好处。

return fetch(url, params).then(response => {
    return response.json().then(body => {
        if (response.status === 200) {
            return body
        } else {
            throw body
        }
    })
})

答案 7 :(得分:0)

我从 this page on MDN 那里得到了解决方案。这对我有帮助。我认为这是因为 API 返回纯文本。

相关问题