【问题标题】:XMLHttpRequest : how to navigate the "Link" headerXMLHttpRequest:如何导航“链接”标头
【发布时间】:2020-10-22 07:23:46
【问题描述】:

上下文

我正在使用XMLHttpRequest 从 GitHub API 请求资源。由于the response is paginated,我想使用提供的Link 标头。

在响应回调中记录request.getResponseHeader("link") 时,我会得到null(如果没有分页)或类似的东西:

<https://api.github.com/repositories/14173222/forks?sort=stargazers&per_page=100&page=2>; rel="next", <https://api.github.com/repositories/14173222/forks?sort=stargazers&per_page=100&page=4>; rel="last"

问题

有没有一种简单的方法来导航这个返回的字符串而无需解析它?

类似于request.getResponseHeader("link").get("next") 的东西,它会返回https://api.github.com/repositories/14173222/forks?sort=stargazers&amp;per_page=100&amp;page=2 .

我的实际目标是提取下一页的编号(例如,我想要一个返回 2 的函数,因为它是要请求的下一页)。

【问题讨论】:

  • 不,没有本地方法可以做到这一点。您必须自己编写或搜索执行此操作的众多库和代码 sn-ps 之一。

标签: javascript http xmlhttprequest http-headers github-api


【解决方案1】:

我不会将此标记为已接受的答案,因为它没有完全回答问题,但这仍然是我最终要做的:

/** Paginated request. Pages index start at 1. */
function request_fork_page(page_number, user, repo, token) {

  // ...

  /* Pagination (beyond 100 forks). */
  const link_header = request.getResponseHeader("link");
  if (link_header) {
    let contains_next_page = link_header.indexOf('>; rel="next"');
    if (contains_next_page !== -1) {
      request_fork_page(++page_number, user, repo);
    }
  }
}

【讨论】:

    猜你喜欢
    • 2018-11-07
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多