使用 fetch() 和 Ticketmaster API,我尝试访问日志中的 [[PromiseValue]],但始终未定义。
const API_key = '1234'
fetch(`https://app.ticketmaster.com/discovery/v2/events.json?size=1&apikey=${API_key}`)
.then(response => console.log(response.json()))
.then(data => console.log(data))
最佳答案
.then(response => console.log(response.json()))
返回 undefined
作为 console.log
方法不返回任何值;
更新您的代码以使用实际值:
选项 1:
fetch(https://app.ticketmaster.com/discovery/v2/events.json?size=1&apikey=${API_key})
.then(response => {
var response = response.json();
console.log(response);
return response;
})
.then(data => console.log(data))
选项 2:
fetch(https://app.ticketmaster.com/discovery/v2/events.json?size=1&apikey=${API_key})
.then(response => response.json())
.then(data => console.log(data))
如果您还想利用从 API 返回的数据,您必须了解数据的形状并定义您想要用它做什么。快速查看他们的文档,如果您想获取查询中返回的第一个事件的名称,您可以将 .then(data => console.log(data))
替换为
.then(data => console.log(data._embedded.events[0].name)) // logs it to the console
或
.then(data => alert(data._embedded.events[0].name)) // creates an alert with the name in it
或
.then(data => {
var ele = document.createElement('div');
ele.innerHTML = data._embedded.events[0].name;
document.querySelector('body').appendChild(ele);
}); // creates a div with the name in it and appends it to your page
关于javascript - 尝试使用 fetch 从 API 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58699970/