javascript - 循环访问通过 URL 链接的 API 结果页面

标签 javascript json api loops

我正在尝试循环遍历 API 结果的所有页面,该结果将下一页作为结果中的 URL 返回:

enter image description here

            const api_url= 'https://wger.de/api/v2/exercise/?format=json&page=29';

                async function getExercises(){
                    const response = await fetch(api_url);
                    const data = await response.json();
                    data.results.forEach( item => console.log(item.name))
                }
                getExercises();

你会如何做这件事?

最佳答案

您可以使用while循环:

async function getExercises () {
  let url = 'https://wger.de/api/v2/exercise/?format=json'

  while (url) {
    const res = await fetch(url)
    const data = await res.json()

    for (const item of data.results) {
      console.log(item.name)
    }

    url = data.next
  }
}

// By the way, always catch errors here, otherwise they will become unhandled rejections!
// This is assuming that this call happens outside of an async function.
getExercises().catch(e => console.error('Failed to get exercises', e))

此外,我做了一个有根据的猜测,您可以指定一个 limit 参数,并对它进行了测试,看起来它有效。因此,您可以通过设置更高的限制来减少所需的请求数量,例如https://wger.de/api/v2/exercise/?format=json&limit=1000(目前有 685 个结果,因此限制为 1000 时,甚至只需要一个请求即可获取所有结果,但当然,您仍然应该使用此代码,以便它可以获取第 2 页,以防有一天超过 1000 页)。

关于javascript - 循环访问通过 URL 链接的 API 结果页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60676166/

相关文章:

javascript - 为色度计生成#CCCCCC 和#3B5998 之间的颜色?

javascript - jQuery json 对象 if 语句

javascript - 从 Destiny Api 解析 JQuery 中的 JSON 对象

json - Alamofire 错误域=NSURLErrorDomain 代码=-999 "cancelled"

api - 对实现 HATEOAS 的 rest API 的权限

api - Magento2:REST API:保存每个商店 View 的产品详细信息不起作用

javascript - 在网站 HTML 页面上搜索文本

在图像上应用 css 过滤器的 Javascript 按钮

json - java.lang.NoSuchFieldError : USE_DEFAULTS thrown while validating json schema through json schema validator

windows - CreateEnvironmentBlock 返回的 block 对于 Windows Vista 上的 CreateProcessWithLogon 来说太大了