gpt4 book ai didi

javascript - 从 ReadableStream 对象中检索数据?

转载 作者:IT老高 更新时间:2023-10-28 21:49:02 25 4
gpt4 key购买 nike

如何从 ReadableStream 对象获取信息?

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

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

fetch('http://192.168.5.6:2000/api/car', obj)
.then((res) => {
if(!res.ok) {
console.log("Failure:" + res.statusText);
throw new Error('HTTP ' + res.status);
} else {
console.log("Success :" + res.statusText);
return res.body // what gives?
}
})

最佳答案

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

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

希望这有助于解决问题。

关于javascript - 从 ReadableStream 对象中检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40385133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com