从 ReadableStream 对象中检索数据?

2022-01-20 00:00:00 reactjs node.js fetch javascript

如何从 ReadableStream 对象获取信息?

How may I get information from a ReadableStream object?

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

I am using the Fetch API and I don't see this to be clear from the documentation.

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

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

推荐答案

为了从 ReadableStream 访问数据,您需要调用其中一种转换方法(可用文档 这里).

In order to access the data from a ReadableStream you need to call one of the conversion methods (docs available 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": "..." }
  });


如果您的数据返回类型不是 JSON,或者您不想要 JSON,请使用 text()


If your data return type is not JSON or you don't want JSON then use 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
  });

希望这有助于解决问题.

Hope this helps clear things up.

相关文章