我如何从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();
})
为了从中访问数据,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
});
希望这有助于清理问题。
某些人可能会发现一个async
有用的示例:
var response = await fetch("https://httpbin.org/ip");
var body = await response.json(); // .json() is asynchronous and therefore must be awaited
json()
converts the response's body from a ReadableStream
to a json object.
The await
statements must be wrapped in an async
function, however you can run await
statements directly in the console of Chrome (as of version 62).
res.json()
returns a promise. Try ...
res.json().then(body => console.log(body));
聚会晚了一点,但是在ReadableStream
使用Sharepoint框架从Odata $ batch请求的产品中获取有用的东西时遇到了一些问题。
遇到了与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()”返回一个承诺。在类似于第二秒的行为中返回“ response.json()”的当时结果。它具有在响应范围内的额外好处。
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))
文章标签:fetch , javascript , node.js , reactjs
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!