使用nodejs实现分页功能
时间: 2023-09-16 22:09:16 浏览: 112
dynamodb-paginator:轻松对 DynamoDB 结果进行分页
1. 安装依赖:`npm install --save express mongoose body-parser ejs`
2. 创建app.js文件并引入依赖:
```javascript
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const ejs = require('ejs');
const app = express();
```
3. 连接数据库:
```javascript
mongoose.connect('mongodb://localhost:27017/mydb', {
useNewUrlParser: true,
useUnifiedTopology: true
});
```
4. 创建数据模型:
```javascript
const Schema = mongoose.Schema;
const PostSchema = new Schema({
title: String,
content: String,
created_at: { type: Date, default: Date.now }
});
const Post = mongoose.model('Post', PostSchema);
```
5. 设置视图引擎:
```javascript
app.set('view engine', 'ejs');
```
6. 设置静态文件目录:
```javascript
app.use(express.static(__dirname + '/public'));
```
7. 解析请求体:
```javascript
app.use(bodyParser.urlencoded({ extended: true }));
```
8. 定义路由:
```javascript
app.get('/', async (req, res) => {
const pageSize = 5; // 每页显示的记录数
const page = req.query.page || 1; // 当前页码,默认为1
const count = await Post.countDocuments(); // 总记录数
const pageCount = Math.ceil(count / pageSize); // 总页数
const posts = await Post.find().skip((page - 1) * pageSize).limit(pageSize); // 查询当前页的记录
res.render('index', { posts, page, pageCount });
});
```
9. 创建视图文件:
```html
<!-- index.ejs -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>分页功能演示</title>
</head>
<body>
<h1>分页功能演示</h1>
<% for(let i = 0; i < posts.length; i++) { %>
<h2><%= posts[i].title %></h2>
<p><%= posts[i].content %></p>
<hr>
<% } %>
<% if(pageCount > 1) { %>
<% if(page > 1) { %>
<a href="/?page=<%= page - 1 %>">上一页</a>
<% } %>
<% if(page < pageCount) { %>
<a href="/?page=<%= page + 1 %>">下一页</a>
<% } %>
<% } %>
</body>
</html>
```
10. 启动应用:
```javascript
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
```
阅读全文