【问题标题】:Fetching API and return Specific data获取 API 并返回特定数据
【发布时间】:2020-04-10 04:06:44
【问题描述】:

所以,我正在尝试从Calendarific 获取API 我获取它并在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 工作正常,但我在从API 访问特定数据时遇到问题我试过holidays[0].name 但它显示undefined 我在这里做错了什么?

【问题讨论】:

  • res -> res.json()
  • 向我们展示数据的样子

标签: javascript json api


【解决方案1】:

接收 JSON 时,而不是

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

使用

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

另外,根据calendarific documentation,你应该先查询一个response键:

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

【讨论】:

  • 好的!谢谢 我明白了 我想在浏览器上显示data 我需要使用res.text() 但现在我很困惑在什么情况下我需要使用res.text()
  • 当你查询的URL返回一个文本时,使用文本,当它是一个json时,使用json
  • 你可以发一个新问题
猜你喜欢
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2018-12-21
  • 2013-09-18
  • 2017-05-26
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多