简体   繁体   中英

How to add pagination to navigate blog post pages (Node/Express)

I am building a blog site and trying to use pagination to navigate the pages of blog posts when there are more than 3 posts stored in the database. I'm trying to pass data from the front-end when clicking "newer" or "previous" buttons to the back-end to control the pages. How can I go about doing that?

I feel like I have to use the POST method somehow.

Here is my front-end code in EJS. These are the buttons that control the pages of posts.

  <% if(totalItems > 3){ %>
  <div class="page-buttons">
    <form action="/">
      <button type="submit" class="btn btn-outline-info newer-posts">Next</button>

    <button type="submit" class="btn btn-outline-info older-posts">Previous</button>
    </form>

  </div>
  <% } %>

Here is the route on the back-end.

app.get("/", (req, res) => {
  let currentPage = req.query.page || 1;
  let perPage = 3;
  let totalItems;

  Post.find()
    .countDocuments()
    .then(count => {
      totalItems = count;
      Post.find()
        .skip((currentPage - 1) * perPage)
        .limit(perPage)
        .then(posts => {
            res.render("home", {
              posts: posts,
              totalItems: totalItems
            });
        });
    })
});

I expect clicking the buttons will increment or decrement the currentPage variable and render the proper pages of blog posts from the back-end. But instead, it does nothing.

Any help would be appreciated.

Since you know the total amount of items (blog posts), you can do some simple math to know what the last page would be.

const lastPage = Math.ceil(totalItems / perPage);

Just like you're passing posts and totalItems , I would also pass currentPage and lastPage . We could essentially do the above math in the template, but why would we?

res.render("home", {
    posts,
    currentPage,
    totalItems,
    lastPage
});
// The above notation is shorthand for prop: value

Now, in the template, we can decide whether to show the previous and next page button based on the variables we passed.

If currentPage is higher than 1, we must be on the second page or beyond, so show a link to the current page ?page=<%= currentPage - 1 %> .

If currentPage is lower than lastPage , we have not reached the end yet, so we show the link to the next page. Which would be ?page=<%= currentPage + 1 %>

There is no need to use a form here. Simple <a> tags will suffice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM