[英]How to get API data using fetch in NodeJS
I have this api which is returning arrays of values:我有这个返回值数组的api:
app.get("/events", (req, res) => {
let response = null;
let authObj = auth.authorize();
setTimeout(() => {
let result = controller.listEvents(authObj);
result.then((data) => {
response = data;
console.log(data)
res.json(response); // is this way of passing this data object to front-end right ???
});
}, 2000);
});
the result of console.log(data)
above looks like below:上面
console.log(data)
的结果如下所示:
[
{
kind: 'calendar#event',
etag: '"3203302285276000"',
id: '69jte9qmoij84irjf2ktlqlqcd',
status: 'confirmed',
htmlLink: 'https://www.google.com/calendar/event?eid=NjlqdGU5cW1vaWo4NGlyamYya3RscWxxY2QgYmFudWthamFuYW5hdGhqYXlhcmF0aG5hQG0',
created: '2020-10-02T15:05:42.000Z',
updated: '2020-10-02T15:05:42.638Z',
summary: 'What’s New in Lens 3.6.0',
},
{
kind: 'calendar#event',
etag: '"3200206562152000"',
id: '_6l6jehjbbtol8him9194uqr88907cjaoct3japrle5a3ii9o6ds62t3kcln68pb5',
status: 'confirmed',
htmlLink: 'https://www.google.com/calendar/event?eid=XzZsNmplaGpiYnRvbDhoaW05MTk0dXFyODg5MDdjamFvY3QzamFwcmxlNWEzaWk5bzZkczYydDNrY2xuNjhwYjUgYmFudWthamFuYW5hdGhqYXlhcmF0aG5hQG0',
created: '2020-09-14T17:07:55.000Z',
updated: '2020-09-14T17:08:01.076Z',
summary: 'Ansible Contributor Summit - New Contributor Workshops',
}
]
And I want to pass this data
to my front-end and iterate over it to display the summary
, status
.我想将此
data
传递给我的前端并对其进行迭代以显示summary
、 status
。
Here's how I get this value to my front-end:以下是我如何将这个值传递给我的前端:
const [data, setData] = useState([]);
useEffect(() => {
fetch("/events").then((res) => {
console.log(res);
setData(res.data);
});
});
But when I try to print data
it gives undefined
但是当我尝试打印
data
它给出了undefined
Can someone please help me?有人可以帮帮我吗?
Thanks!谢谢!
The parameter is a Response.该参数是一个响应。 It is not the result of the request, it only contains the headers.
它不是请求的结果,它只包含标头。 You need
你需要
const [data, setData] = useState([]);
useEffect(() => {
fetch("/events").then(res => res.json()).then((res) => {
console.log(res);
setData(res);
});
}, []);
Remember the empty dependency array.记住空的依赖数组。 You don't want to fetch every time the component renders, only once.
您不想在组件呈现时每次都获取一次,而只获取一次。
The result doesn't have a data property, it's just an array.结果没有数据属性,它只是一个数组。 So use
setData(res);
所以使用
setData(res);
, not setData(res.data);
, 不是
setData(res.data);
Give this a shot, because you are expecting json试一试,因为你期待 json
const [data, setData] = useState([]);
useEffect(() => {
fetch("/events").then((res) => {
return res.json()
}).then((responseJson) => {
console.log(responseJson);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.