使用 Github API 创建分页并表示

Create a pagination with Github API and express

我目前正在用 Express 和 Node 创建我的第一个小应用程序,它允许我使用 API 浏览来自 github 的所有存储库。现在一切正常,但当然,我输入搜索的一些关键字会给我 17k 或更多的结果,这取决于我的搜索词的流行程度。现在的问题是:

如何创建分页?默认情况下,API returns 30 results PER PAGE,这个可以改成我喜欢的,如果我只想要一个结果per page.The information,有多少页可以查到据我所知,在 HTTP header 中。 我从他们的文档中了解到我需要从 http header 中提取 link 信息,如下所示:

curl -I "https://api.github.com/search/repositories?q=tetris"

结果:

HTTP/1.1 200 OK
Server: GitHub.com
Date: Fri, 19 Jan 2018 14:55:44 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 170353
...
X-GitHub-Media-Type: github.v3; format=json
Link: <https://api.github.com/search/repositories?q=pokemon&page=2>; rel="next", <https://api.github.com/search/repositories?q=pokemon&page=34>; rel="last"

我感兴趣的是 link 部分,它为我提供了有关下一页的信息,以及一般有多少页。我现在找到的所有 tuts 都是基于数据库的结果和来自表或模式的提取信息。我只是不太明白我现在是如何将 curl 信息解析为 express 的,或者我还有其他的可能性。我尝试使用 req.headers,这给了我

{ host: 'localhost:3000',
  connection: 'keep-alive',
  'upgrade-insecure-requests': '1',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
  referer: 'http://localhost:3000/github',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7' }

这不是我所希望的。

我当前的路线是这样的:

app.get('/github/results', function (req, res) {
var query = req.query.gitHubsearch;
var options = {headers: {'User-Agent':'request'}};
var pageSize = 25;
var apiCall = 'https://api.github.com/search/repositories?q=' + query + '&order=desc+&per_page=' + pageSize;
request.get(apiCall, options, function (error, response, body) {
    if(!error && response.statusCode == 200) {
      var githubData = JSON.parse(body);
      console.log(req.headers);
      res.render("./github/results", {githubData: githubData});
    }
  });
});

我希望有人能给我一些提示,告诉我我必须看什么方向,或者我现在如何在 NodeJS 中创建这种分页。

您似乎在调用 req.header,它使用的是向您的 API 发出的请求的请求对象,而不是来自 github [=25= 的响应] 打电话。

如果您查看 app.get 行,您会根据 express 标准定义 req 和 res。这与向您的服务器发出的请求有关。对请求库的调用然后进行 HTTP 调用,然后调用回调函数填充 error, response, body 以及您的调用详细信息,直到 github.

如果你这样做 console.log(response.headers) 你应该在那里找到 link 项目,你可以通过 response.headers.link.

访问它

看起来您只是有点混淆了 API 的请求和响应对象与 GitHub API 的请求和响应对象。这是一些简单的代码,您应该可以 运行 看看您的期望。

const request = require('request');

app.get('/github/result', function(req, res) {
    const endpoint = "https://api.github.com/search/repositories?q=" + query + "&order=desc+&per_page=" + pageSize;

    request.get(
      endpoint,
      { headers: { "User-Agent": "request" } },
      function(err, res, body) {
        console.log(err);
        console.log(res.headers);
      }
    );
});