首页 > 解决方案 > 获取 API 并返回特定数据

问题描述

所以,我试图APICalendarific中获取我获取它,我在console这里获取数据是下面的代码:

btn.addEventListener('click', function fetchApi(){
fetch('https://calendarific.com/api/v2/holidays?&api_key=<myKey>&country=US&year=2019')
.then(res => res.text())
.then(data => {
    //holiday.innerHTML = data;
    //console.log(data);
    console.log(data.holidays[0].name)
})
 .catch(err => console.log(err));
  // alert('click')
});

但我想访问特定的数据。我只想访问name,我该怎么做?工作正常,但我在尝试Code访问特定数据时遇到了问题,但它显示了我在这里做错了什么?APIholidays[0].nameundefined

标签: javascriptjsonapi

解决方案


接收 JSON 时,而不是

.then(res => res.text())
.then(...

利用

.then(res => res.json())
.then(...

此外,根据calendarific 文档response您应该首先查询一个键:

console.log(data.response.holidays[0].name)

推荐阅读