[英]How to get API data using fetch in NodeJS
我有这个返回值数组的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);
});
上面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',
}
]
我想将此data
传递给我的前端并对其进行迭代以显示summary
、 status
。
以下是我如何将这个值传递给我的前端:
const [data, setData] = useState([]);
useEffect(() => {
fetch("/events").then((res) => {
console.log(res);
setData(res.data);
});
});
但是当我尝试打印data
它给出了undefined
有人可以帮帮我吗?
谢谢!
该参数是一个响应。 它不是请求的结果,它只包含标头。 你需要
const [data, setData] = useState([]);
useEffect(() => {
fetch("/events").then(res => res.json()).then((res) => {
console.log(res);
setData(res);
});
}, []);
记住空的依赖数组。 您不想在组件呈现时每次都获取一次,而只获取一次。
结果没有数据属性,它只是一个数组。 所以使用setData(res);
, 不是setData(res.data);
试一试,因为你期待 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.