javascript - 获取 API 并返回特定数据
问题描述
所以,我试图API
从Calendarific中获取我获取它,我在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
解决方案
接收 JSON 时,而不是
.then(res => res.text())
.then(...
利用
.then(res => res.json())
.then(...
此外,根据calendarific 文档,response
您应该首先查询一个键:
console.log(data.response.holidays[0].name)
推荐阅读
- c# - Flutter - HttpClient 适用于应用程序,但不适用于浏览器。.NET Core 3.1 WebAPI + Flutter2
- python - 根据列名刮取表格行
- c# - Xamarin 中 UITableViewCell 中的选择器
- node.js - Modus TCP 字节到标准数据类型
- javascript - 将 Ipc 从 Vue js 发送到 Electron
- sql - SQL,如何组合记录
- entity-framework-core - 使用 AutoMapper 在 Entity Framework Core 中进行多对一映射
- laravel - Laravel - 如何根据需要验证电话的任一电子邮件
- java - 在java中继承final方法有什么用?如果我们不能覆盖它
- python - 如何转换矩阵并保存到 csv 文件