用express进行节点分页 [英] Node pagination with express

查看:118
本文介绍了用express进行节点分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须构建API并将其作为服务器端,应该在10个条目的页面中提供结果,仅使用带有express的Node(不使用其他软件包).

I have to build and API as server side, that should provide results in pages of 10 entries, using only Node with express (no other packages).

  • 查询参数p指定从1开始返回的页面.如果省略p参数,则默认值为1.
  • 如果客户端要求提供/api/stories?p=1,则他们应该只能从最新的故事开始获得10个故事.

  • A query parameter p specifies which page to return, starting with 1. If the p parameter is omitted, the default value is 1.
  • If the client side asks for /api/stories?p=1, they should only get 10 stories, starting from the newest one.

如果为p=2,则API必须返回第二批10个故事. 返回故事页面时,必须先排列最新故事.

If p=2, the API must return the second batch of 10 stories. When a page of stories is returned it must be ordered with the most recent story first.

如果p大于最后一个页面号,则API必须返回最后一个可用页面.

If p is greater than the last page number, the API must return the last available page.

page值是当前返回的页面.如果请求的页面p大于最后一个页面号,则返回的page值将指示最后一个页面号.

The page value is the currently returned page. If the requested page p is greater than the last page number, the returned page value will indicate the last page number.

这就是我的分页...

This is what I have for pagination...

//pagination
const pageLimit = 10;
app.get('/api/posts', function(req, res) {
  res.json({
    "posts": posts.slice(-pageLimit).reverse(),
    "page": 1,
    "pageCount": Math.ceil(posts.length / 10)
  });
});

返回正确的结果是每页10个帖子,第2、3页上的第11、21、31个帖子被推送... 现在,当我尝试从第1页前进到第2页(作为下一页)时,我的问题来了……

The return is correct as 10 posts per page, 11th, 21st, 31st posts are pushed on 2nd ,3rd page etc... Now my problem comes when I try to advance from page 1 to page 2 (as a next page) nothing happens...

我猜我必须实现下一个,但是我不知道该怎么做

I'm guessing I have to implement something like a a next but I don't have any idea how to do it

任何帮助将不胜感激...

Any help would be appreciated...

推荐答案

挠了两天后,我找到了一个对我有用的解决方案.谢谢 num8er 为我指明了正确的方向...

after scratching my head 2 days, I found a solution that works for me..Thank you num8er for pointing me in right direction...

app.get('/api/posts', (req, res) => {
  const pageCount = Math.ceil(posts.length / 10);
  let page = parseInt(req.query.p);
  if (!page) { page = 1;}
  if (page > pageCount) {
    page = pageCount
  }
  res.json({
    "page": page,
    "pageCount": pageCount,
    "posts": posts.slice(page * 10 - 10, page * 10)
  });
});

这篇关于用express进行节点分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆