CRUD案例

Posted So istes immer

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CRUD案例相关的知识,希望对你有一定的参考价值。

目录

页面样式可以去Express官网找一个基本模板

1.路由设计

请求方法请求路径携带参数备注
GET/students渲染首页
GET/students/new渲染添加学生页面
POST/studentsname,age,gender,hobbies处理添加学生页面
GET/students/edit渲染编辑页面
POST/students/editid,name,age,gender,hobbies处理编辑请求
GET/students/delete处理删除请求

2.要安装的包 

  "dependencies": {
    "art-template": "^4.13.2",
    "body-parser": "^1.19.0",
    "bootstrap": "^5.1.3",
    "express": "^4.17.1",
    "express-art-template": "^1.0.1"
  }

3.具体代码

文件结构

  

app.js

const express = require('express')
const app = express()
const router = require('./router')
const bodyParser = require('body-parser')
 
app.use('/public/', express.static('./public/'))
app.use('/node_modules/', express.static('./node_modules/'))

app.engine('html', require('express-art-template'))

// 配置模板引擎和body-parser一定要在挂载路由之前
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// 把路由容器挂载到app服务中
app.use(router)

app.listen(3000, function () {
	console.log('running at port 3000...')
})

router.js

const express = require('express')
var Student = require('./student')

// 1. 创建一个路由容器
const router = express.Router()

// 2. 把路由都挂载到router路由容器中
router.get('/students', function (req, res) {
	Student.find(function (err, students) {
		if (err) {
			return res.status(500).send("Server Error.")
		}
		res.render('index.html', {
			students: students
		})
	})
})

router.get('/students/new', function (req, res) {
	res.render('new.html')
})

router.post('/students', function (req, res) {
	Student.save(req.body, function(err) {
		if (err) {
			return res.status(500).send('Server Error.')
		}
		res.redirect('/students')
	})
})

router.get('/students/edit', function (req, res) {	
	Student.findById(parseInt(req.query.id), function(err, student) {
		if (err) {
			return res.status(500).send('Server error.')
		}
		res.render('edit.html', {
			student: student
		})
	})
})

router.post('/students/edit', function (req, res) {
	// 1.获取表单数据 2.更新 3.发送响应
	Student.updateById(req.body, function (err) {
		if (err) {
			return res.status(500).send('Server error.')
		}
		res.redirect('/students')
	})
})

router.get('/students/delete', function (req, res) {	
	Student.deleteById(req.query.id, function(err) {
		if(err) {
			return res.status(500).send('Server error.')
		}
		res.redirect('/students')
	})
})

//3. 把路由导出
module.exports = router

student.js

/**
 * 数据操作文件模块
 * 职责: 操作文件中的数据,只处理数据,不关心业务
 */

const fs = require('fs')

const dbPath = './db.json'

/**
 * 获取所有学生列表  
 */
exports.find = function (callback) {
	fs.readFile(dbPath, 'utf-8', function (err, data) {
		if (err) {
			return callback(err)
		}
		callback(null, JSON.parse(data).students)
	})
}

/**
 * 根据Id获取学生信息对象
 */
exports.findById = function (id, callback) {
	fs.readFile(dbPath, 'utf-8', function (err, data) {
		if (err) {
			return callback(err)
		}
		var students = JSON.parse(data).students
		var ret = students.find(function (item) {
			return item.id === parseInt(id)
		})
		callback(null, ret)
	})
}

/**
 * 添加保存学生  
 */
exports.save = function (student, callback) {
	fs.readFile(dbPath, 'utf-8', function (err, data) {
		if (err) {
			return callback(err)
		}
		var students = JSON.parse(data).students
		// 处理id唯一的,不重复
		student.id = students[students.length - 1].id + 10
		// 把用户传递的对象保存到数组中
		students.push(student)
		// 把对象数据转换为字符串
		var fileData = JSON.stringify({
			students: students
		})
		// 把字符串保存到文件中
		fs.writeFile(dbPath, fileData, function (err) {
			if (err) {
				return callback(err)
			}
			callback(null)
		})
	})
}

/**
 * 更新学生  
 */
exports.updateById = function (student, callback) {
		fs.readFile(dbPath, 'utf-8', function (err, data) {
		if (err) {
			return callback(err)
		}
		var students = JSON.parse(data).students

		student.id = parseInt(student.id)
		student.age = parseInt(student.age)
		student.gender = parseInt(student.gender)

		var stu = students.find(function (item) {
			return item.id === student.id
		})
		for (let item in student) {
			stu[item] = student[item]
		}
		var fileData = JSON.stringify({
			students: students
		})
		fs.writeFile(dbPath, fileData, function (err) {
			if (err) {
				return callback(err)
			}
			callback(null)
		})
	})
}

/**
 * 删除学生  
 */
exports.deleteById = function (id, callback) {
	fs.readFile(dbPath, 'utf-8', function (err, data) {
		if (err) {
			return callback(err)
		}
		var students = JSON.parse(data).students
		var deleteId = students.findIndex(function(item) {
			return item.id === parseInt(id)
		})
		// 根据下标从数组中删除对应的学生
		students.splice(deleteId, 1)
		var fileData = JSON.stringify({
			students: students
		})
		fs.writeFile(dbPath, fileData, function (err) {
			if (err) {
				return callback(err)
			}
			callback(null)
		})
	})
}

db.json(存放数据的文件)

{
	"students": [
		{"id": 1, "name": "张三", "gender": 0, "age": 18, "hobbies": "看动漫"},
		{"id": 2, "name": "李四", "gender": 1, "age": 17, "hobbies": "听音乐"},
		{"id": 3, "name": "王五", "gender": 1, "age": 19, "hobbies": "看电影"},
		{"id": 4, "name": "赵六", "gender": 0, "age": 19, "hobbies": "看小说"},
		{"id": 5, "name": "钱七", "gender": 1, "age": 20, "hobbies": "运动"}
	]
}

views/index.html

<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <title>Dashboard Template for Bootstrap</title>
    <link href="/node_modules/bootstrap/dist/css/bootstrap.css" rel="stylesheet">
    <style>
    	body {
  			padding-top: 50px;
			}
			.main {
  			padding: 20px;
			}
    </style>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <h2 class="sub-header">学生信息表</h2>
          <a class="btn btn-success" href="/students/new">添加学生</a>
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>学号</th>
                  <th>姓名</th>
                  <th>性别</th>
                  <th>年龄</th>
                  <th>爱好</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
              	{{ each students }}
              	<tr>
                  <td>{{ $value.id }}</td>
                  <td>{{ $value.name }}</td>
                  <td>{{ $value.gender }}</td>
                  <td>{{ $value.age }}</td>
                  <td>{{ $value.hobbies }}</td>
                  <td>
                    <a href="/students/edit?id={{ $value.id }}">编辑</a>
                    <a href="/students/delete?id={{ $value.id }}">删除</a>
                  </td>
                </tr>
              	{{ /each}} 
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

views/new.html

<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <title>Dashboard Template for Bootstrap</title>
    <link href="/node_modules/bootstrap/dist/css/bootstrap.css" rel="stylesheet">
    <style>
    	body {
  			padding-top: 50px;
			}
			.main {
  			padding: 20px;
			}
    </style>
  </head>
  <body>
    <div class="container-fluid">
      <h3 class="sub-header">添加学生</h3>
      <form action="/students" method="post">
        <div class="form-group">
          <label for="name">姓名</label>
          <input type="text" class="form-control" name="name">
        </div>
        <div class="form-group">
          <label for="name">性别</label>
          <div>
            <label class="radio-inline">
              <input type="radio" name="gender" id="radio1" value="0" checked>男
            </label>
            <label class="radio-inline">
              <input type="radio" name="gender" id="radio2" value="1">女
            </label>
          </div>
        </div>
        <div class="form-group">
          <label for="age">年龄</label>
          <input type="number" class="form-control" name="age">
        </div>
        <div class="checkbox">
          <label for="name">爱好</label>
          <input type="text" class="form-control" name="hobbies">
        </div>
        <button type="submit" class="btn btn-success">Submit</button>
      </form>
    </div>
  </body>
</html>

views/edit.html

<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <title>Dashboard Template for Bootstrap</title>
    <link href="/node_modules/bootstrap/dist/css/bootstrap.css" rel="stylesheet">
    <style>
    	body {
  			padding-top: 50px;
			}
			.main {
  			padding: 20px;
			}
    </style>
  </head>
  <body>
    <div class="container-fluid">
      <h3 class="sub-header">编辑学生</h3>
      <form action="/students/edit" method="post">
        <!-- 这里的id需要上传到服务器,但是又不希望被看见 -->
        <input type="hidden" name="id" value="{{ student.id }}">
        <div class="form-group">
          <label for="name">姓名</label>
          <input type="text" class="form-control" name="name" value="{{ student.name }}">
        </div>
        <div class="form-group">
          <label for="name">性别</label>
          <div>
            <label class="radio-inline">
              <input type="radio" name="gender" id="radio1" value="0">男
            </label>
            <label class="radio-inline">
              <input type="radio" name="gender" id="radio2" value="1">女
            </label>
          </div>
        </div>
        <div class="form-group">
          <label for="age">年龄</label>
          <input type="number" class="form-control" name="age" value="{{ student.age }}">
        </div>
        <div class="checkbox">
          <label for="name">爱好</label>
          <input type="text" class="form-control" name="hobbies" value="{{ student.hobbies }}">
        </div>
        <button type="submit" class="btn btn-success">Submit</button>
      </form>
    </div>
    <script>
      var radio1 = document.getElementById("radio1")
      var radio2 = document.getElementById("radio2")
      if({{ student.gender }} === 0) {
        radio1.checked = true
      } else {
        radio2.checked = true
      }
    </script>
  </body>
</html>

效果

以上是关于CRUD案例的主要内容,如果未能解决你的问题,请参考以下文章

python3操作MongoDB的crud以及聚合案例,代码可直接运行(python经典编程案例)

11SpringBoot-CRUD-thymeleaf公共页面元素抽取

springboot+influxdb实现crud操作案例

springboot 整合mybaits实现crud操作(含分页)案例

CRUD案例

layui的CRUD案例