默认情况下如何在主页上显示分页的api表

时间:2019-11-03 23:41:11

标签: node.js pagination ejs

在我的Node js + Ejs + Postgres应用程序中,我设法创建了分页API并在html上显示结果,但是只有在页面呈现并且单击分页按钮时,我才能看到正确的数据(使用:bootstrap 4)。

当我使用以下代码时,我的分页API可以工作

http://localhost:3000/?page=3&limit=2

然后表显示成功

但是我已经定义了app.get(“ /”),我想在使用时查看分页表:

http://localhost:3000/

有没有机会得到这个?

//index.js
app.get("/", (req, res, next) => {
  pool.connect((err, client, done) => {
    const query = "SELECT * FROM weight_log order by date desc";
    client.query(query, (error, result) => {
      done();
      if (error) {
        res.status(400).json({ error });
      }
      if (result.rows < "1") {
        res.status(404).send({
          status: "Failed",
          message: "No weight information found"
        });
      } else {
        req.weight = result.rows;

        const resultWeight = req.weight;
        const page = parseInt(req.query.page);
        const limit = parseInt(req.query.limit);
        const startIndex = (page - 1) * limit;
        const endIndex = page * limit;
        const results = {};

        if (endIndex < resultWeight.length) {
          results.next = {
            page: page + 1,
            limit: limit
          };
        }

        if (startIndex > 0) {
          results.previous = {
            page: page - 1,
            limit: limit
          };
        }

        results.results = resultWeight.slice(startIndex, endIndex);
        res.render("index", {
           data: results
        });
      }
    });
  });
});
// index.ejs
<div class="container">
     <table class="table table-striped">
        <tr>
          <th>date:</th>
          <th>weight:</th>
        </tr>
        <% for(var i=0; i < data.results.length; i++) { %>
        <tr>
          <td>
            <%= data.results[i].date %>
          </td>
          <td>
            <%= data.results[i].weight %>
          </td>
        </tr>

        <% } %>
      </table>

      <ul class="pagination justify-content-center">
        <li class="page-item">
          <a class="page-link" href="/?page=1&limit=2">1</a>
        </li>
        <li class="page-item">
          <a class="page-link" href="/?page=2&limit=2">2</a>
        </li>
        <li class="page-item">
          <a class="page-link" href="/?page=3&limit=2">3</a>
        </li>
        <li class="page-item">
          <a class="page-link" href="/">main</a>
        </li>
      </ul>
    </div>

0 个答案:

没有答案