尝试使用提取从API获取数据

我正在使用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))
quanlong123456 回答:尝试使用提取从API获取数据

.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

OR

.then(data => alert(data._embedded.events[0].name)) // creates an alert with the name in it

OR

.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
本文链接:https://www.f2er.com/3164177.html

大家都在问