从 ReadableStream 对象中检索数据?

Retrieve data from a ReadableStream object?

如何从 ReadableStream 对象获取信息?

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

正文作为 ReadableStream 返回,我只想访问此流中的 属性。在浏览器开发工具中的 Response 下,我似乎将此信息以 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();
    })

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

编辑: 如果您的数据 return 类型不是 JSON 或者您不想要 JSON 然后使用 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
  });

希望这有助于解决问题。

res.json()returns一个承诺。尝试...

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

有些人可能会发现 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 的控制台中 运行 await 语句(如版本 62).

聚会有点晚了,但在使用 Sharepoint 框架从 Odata $batch 请求生成的 ReadableStream 中获取有用的东西时遇到了一些问题。

与 OP 有类似的问题,但我的解决方案是使用与 .json() 不同的转换方法。在我的例子中 .text() 就像一个魅力。然而,为了从文本文件中获得一些有用的东西 JSON,需要进行一些调整。

如果您只想将响应作为文本而不想将其转换为 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);
  });

我不喜欢那个链接。第二个则无权访问状态。如前所述'response.json()'returns一个承诺。在类似于第二个 then 的行为中返回 'response.json()' 的 then 结果。它具有在响应范围内的额外好处。

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

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

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))

在阅读下一篇之前,我遇到了同样的问题超过 12 个小时,以防万一这对任何人都有帮助。在您的 _api 页面中使用 nextjs 时,您需要使用 JSON.stringify(whole-response) 然后使用 res.send(JSON.stringify(whole-response 将其发送回您的页面)) 并且在客户端收到它时,您需要将其转换回 json 格式,以便它可用。这可以通过阅读他们的序列化部分来理解。希望对你有帮助。