小编典典

从 ReadableStream 对象中检索数据?

all

如何从ReadableStream对象中获取信息?

我正在使用 Fetch API,但从文档中看不出这一点。

正文作为 a 返回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();
    })

阅读 151

收藏
2022-05-16

共1个答案

小编典典

为了从 a
访问数据,ReadableStream您需要调用其中一种转换方法(此处提供的文档)。

举个例子:

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

编辑: 如果您的数据返回类型不是 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
  });

希望这有助于澄清事情。

2022-05-16