Home > Software design >  express.js pagination duplicated parameters when you click the page
express.js pagination duplicated parameters when you click the page

Time:10-10

I have created a html page to filter some data in MongoDb and render the data to a display page. And set pagination in the display page. Whenever I choose a new page number, the URL append the page number in the pagination.

Index.js

  let results = await db.collection("bookings").find(whereClause,
    {
      limit: perPage,
      skip: perPage * (Math.max(req.query.page - 1, 0) || 0)
    }
    ).toArray();

  var fullUrl = req.protocol   '://'   req.get('host')   req.originalUrl;

return res.render('search', { bookings: results, pages: pages, perPage: perPage, fullUrl:fullUrl });

Pagination Page:

  <nav aria-label="Page navigation example">
    <ul >
      <% for (var i = 1; i <= pages; i  ) { %>
        <li ></li>
          <a  href="<%=fullUrl%>&perPage=<%=perPage%>&page=<%= i %>">
            <%= i %>
          </a>
        </li>
      <% } %>
    </ul>
  </nav>

The problem is every time when I click a new page number in the pagination, it will append the perPage and page parameter into the original link.

http://localhost:3000/search?numTickets=1&name=somename&perPage=6&page=5&perPage=6&page=3

CodePudding user response:

Try to remove the perPage and page parameters from the fullUrl before returning it:

let results = await db
  .collection('bookings')
  .find(whereClause, {
    limit: perPage,
    skip: perPage * (Math.max(req.query.page - 1, 0) || 0),
  })
  .toArray();

var newUrl = req.protocol   '://'   req.get('host')   req.baseUrl;
var fullUrl = req.protocol   '://'   req.get('host')   req.originalUrl;

const urlSplit = fullUrl.split('?');
if (urlSplit.length > 1) {
  const queryParams = urlSplit[1]
    .split('&')
    .map((q) => {
      const split = q.split('=');
      if (split.length < 2 || split[0] === 'perPage' || split[0] === 'page')
        return '';
      return q;
    })
    .filter(q => q != '')
    .join('&');
  newUrl  = '?'   queryParams;
}

return res.render('search', {
  bookings: results,
  pages: pages,
  perPage: perPage,
  fullUrl: newUrl,
});

CodePudding user response:

Parse the original URL into an URL instance. Then you can more easily manipulate the searchParams

const fullUrl = new URL(
  `${req.protocol}://${req.get("host")}${req.originalUrl}`
);
fullUrl.searchParams.set("perPage", perPage);
fullUrl.searchParams.delete("page");

return res.render("search", {
  bookings: results,
  pages,
  fullUrl: fullUrl.toString(),
});

and in your template...

<% for (var i = 1; i <= pages; i  ) { %>
<li >
  <a  href="<%=fullUrl%>&amp;page=<%=i%>">
    <%= i %>
  </a>
</li>
<% } %>
  • Related