逻辑思想在最下面
index.js
const express = require("express")
const path = require("path")
const app = express()
const fs = require("fs/promises")
//配置请求体解析
app.use(express.urlencoded({ extendeds: true }))
//设置数组
let studentsarr = require("./data/students.json")
//设置路由
app.get("/student", (req, res) => {
res.render("student", { stus: studentsarr })
})
//将ejs设置为默认的模板引擎
app.set("view engine", "ejs")
//配置模板路径,无论控制台还是f5均可
app.set("views", path.resolve(__dirname, "views"))
//配置添加学生的路由
app.post("/addstudent", (req, res) => {
//生成一个id。.at(-1)是数组最后一个
const id = studentsarr.at(-1) ? studentsarr.at(-1).id + 1 : 1
//获取用户输入的信息
const newuser = {
id,
name: req.body.name,
age: req.body.age,
gender: req.body.gender,
address: req.body.address,
}
studentsarr.push(newuser)
//将数据写入到json文件中
fs.writeFile(
path.resolve(__dirname, "./data/students.json"),
JSON.stringify(studentsarr)//
).then(() => {
// 4. 返回响应
// res.send("添加成功!")
// 直接在添加路由中渲染ejs,会面临表单重复提交的问题
res.redirect("/student")
}).catch(() => {
res.send("输入错误")
})
//console.log(newuser);
})
//配置删除学生的路由
app.get("/delete", (req, res) => {
//获取学生学号
const id = req.query.id
console.log(id);
studentsarr = studentsarr.filter((stu) => stu.id != id)//filter它用于把Array的某些元素过滤掉,然后返回剩下的元素。
//wiritefile将数据写入到json文件中
fs.writeFile(
path.resolve(__dirname, "./data/students.jsaon"),
JSON.stringify(studentsarr)//转化为字符串
).then(() => {
// 4. 返回响应
// res.send("添加成功!")
// 直接在添