[英]How to read data from URL using JavaScript?
I want to read data from URL using JavaScript.我想使用 JavaScript 从 URL 读取数据。
below is my code,下面是我的代码,
function Parent() {
const [data, setData] = React.useState(null);
const url = 'someurl';
React.useEffect(() => {
fetch(url)
.then(res => JSON.stringify(res))
.then(data => setData(data);
});
if (data) {
console.log('data', data);
}
}
logging the data state would give the result like below,记录数据状态将给出如下结果,
{
"count": 2,
"results": [{
"title": "title1",
"characters": [
"character1",
],
},
{
"title": "title2",
"characters": [
"character3",
],
},
]
}
How can I read results object from URL?如何从 URL 读取结果对象?
You don't do你不做
fetch(url)
.then(res => JSON.stringify(res))
//...
Instead you do相反,你做
fetch(url)
.then(res => res.json())
//...
Reason being that res
is a Response
see MDN which contains more than just the data you're interested in (the response body).原因是
res
是一个Response
see MDN ,它包含的不仅仅是您感兴趣的数据(响应正文)。
simply简单地
fetch(url)
.then(res => res.json())
.then(data => setData(data))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.