从ReadableStream对象中检索数据?
我如何从ReadableStream对象获取信息?
我正在使用Fetch API,而我从文档中看不到这一点。
正在作为一个ReadableStream返回正文,我只想访问此stream中的属性。 在浏览器开发工具的响应下,我似乎将这些信息以Javascript对象的forms组织到属性中。
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
访问数据,您需要调用其中一种转换方法(文档可在此处获得 )。
举个例子:
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": "..." } });
希望这有助于澄清事情。
res.json()
返回一个promise。 试试…
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的控制台(从版本62开始)运行await
语句。