javascript - 如何解析利用fetch请求的数据
本文介绍了javascript - 如何解析利用fetch请求的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
描述:
利用fetch发起一个ajax请求,请求api返回的用户信息,response中的body并没有我所需要的json信息,查看资料,fetch()请求获取的内容是一个 Stream 对象,这个Stream对象如何解析,最终拿到body中的json信息
var url='http://api.com/getUserInfo';
fetch(url,{
method:'GET',
mode:'cors',// 避免cors攻击
credentials: 'include'
}).then(function(response) {
//打印返回的json数据
//console.log(response) //状态信息
//console.log(response.json()) //一个promise对象
//console.log(response.json().data) //报错了
//如何打印出body中的json信息
response.json().then(function(data){
console.log(data);
});
}).catch(function(e) {
console.log("Oops, error");
});
继续then,就可以打印出数据
response.json().then(function(data){
console.log(data);
});
解决方案
var url='http://api.com/getUserInfo';
fetch(url,{
method:'GET',
mode:'cors',// 避免cors攻击
credentials: 'include'
}).then(function(response) {
//打印返回的json数据
response.json().then(function(data){
console.log(data);
});
}).catch(function(e) {
console.log("Oops, error");
});
这篇关于javascript - 如何解析利用fetch请求的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文