【问题标题】:Trying to get data from an API using fetch尝试使用 fetch 从 API 获取数据
【发布时间】:2019-11-04 19:37:11
【问题描述】:

使用 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))

【问题讨论】:

  • 这段代码是否以某种方式失败?究竟是什么不工作?
  • 对不起,我不得不重新提出这个问题,因为我还没有到那一步。我目前正在尝试使用此 API 执行的操作是在日志中访问 [[PromiseValue]],但我无法定义。
  • 目前还不清楚你在描述什么。什么是“[[PromiseValue]]”?服务器在这个请求中返回了什么?

标签: javascript api fetch


【解决方案1】:

.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

【讨论】:

  • 谢谢,现在我将如何从日志中访问数据?抱歉,我是一名新程序员,使用 API 对我来说是一个全新的挑战。
  • 很乐意提供帮助,但我不清楚您要做什么。您不会访问日志中的数据。日志记录是一种有用的工具,可以帮助您在遇到问题时找出正在发生的事情。在data => console.log(data) 行中,数据是你的数据,所以你可以在那里做任何你想做的事情。您可以将其记录到控制台(如上所述)或其他方式,但您需要提供更多详细信息才能获得更多帮助。
  • 好的,我正在尝试访问 Ticketmaster API 中的数据,但我不确定接下来的步骤是什么。我知道这是一个非常普遍的问题,但更具体地说,我正在尝试在 Ticketmaster API 中启用事件搜索。
  • 用一些选项更新了我的答案,但你仍然没有那么具体。希望对您有所帮助。
猜你喜欢
  • 2019-10-16
  • 1970-01-01
  • 2022-01-20
  • 2020-07-13
  • 2019-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多