Node express 学生端增删改查

2 篇文章 0 订阅
1 篇文章 0 订阅

 

目录

 安装模块

index.js

studentRouter.js

studentRouter.html

datas.json

addstudent.html

updatestudent.html


安装模块

npm init -y

//安装express模块
npm install express --save  

//安装art-template模块
npm install art-template --save
npm install express-art-template --save

//安装第三方中间件
npm install body-parser --save

index.js

1、导入express模块  添加监听

//导入express模块
const express = require("express");
//创建http服务对象
const app = express();


//添加监听
app.listen("8080",function(){
    console.log("running...");
})

2、静态资源的设置 

//导入path的系统模块
const path = require("path");
//获取项目目录
let proname=path.dirname(__dirname); 
//静态资源的设置
app.use("/static",express.static("./views/"));
app.use("/js",express.static(path.join(proname,"js")));
app.use("/css",express.static(path.join(proname,"css")));
app.use("/img",express.static(path.join(proname,"img")));

3、导入body-Parser的第三方中间件  把解析对象挂载到服务器端

//导入body-Parser的第三方中间件
const bodyParser = require("body-parser");

//解析请求参数的类型是application/x-wwww-urlencoded  默认为该类型   
//body-parser专门处理请求正文(请求体))中的内容  把解析好的数据设置到请求对象中body属性中。
app.use(bodyParser.urlencoded({extended:true}));
//解析请求参数的类型是application/json
app.use(bodyParser.json());

4、导入art-template模板引擎 

//导入art-template模板引擎
//设置模板引擎文件后缀,在express框架中整合art-template模板引擎
app.engine("html",require("express-art-template"));
//设置模板引擎目录
app.set("views","./views/");
//设置视图引擎
app.set("view engine","html");

5、导入studentRouter.js模块

//导入studentRouter.js模块
const studentRouter = require("./studentRouter.js");

//根据客户端的资源名称 挂载到studentRouter对象上
 app.use("/student",studentRouter);
 

studentRouter.js

1、导入express模块  创建Router对象 导入json模块

//导入express模块
const express = require("express");

//创建Router对象
const router = express.Router();

//导入datas.json模块
const datas = require("./json/datas.json");



//导出
module.exports = router;

2、//查询功能

//查询功能  http://localhost:8080/student/query   http://localhost:8080/student/
router.get("/query",function(req,resp){
    let obj={};
    obj.studentlist=datas;
    obj.num = datas.length;
    //调用响应对象中的render方法把数据在模板页面动态渲染
    //参数1:模板页面名称
    //参数2:模板页面上要渲染的数据
    resp.render("studentlist.html",obj);

    //直接打开模板页面---》静态页面  原样输出
    //http://localhost:8080/static/studentlist.html
    //通过资源访问模板页面---->把数据在模板页面上进行渲染   动态页面   
    //http://localhost:8080/student/query
})

3、新增保存功能

//新增保存功能
router.post("/add", function (req, resp) {
    let succ = false;
    //取得请求体中的参数
    var params = req.body;
    console.log(params);
    //check 学号不能重复
    for (let i = 0; i < datas.length; i++) {
        if (params.sno == datas[i].sno) {
            succ = true;
            break;
        }
    }
    if (succ) {
        resp.send("该学号已经存在不能新增");
    } else {
        //把数据更新datas.json文件中 写文件
        datas.push(params);
        //把数组对象转换成json字符串写到文件中
        let resultContent = JSON.stringify(datas, null, 4);
        //fs.writeFile("./json/datas.json")
        fs.writeFile(path.join(__dirname, "json", "datas.json"), resultContent, function (err) {
            if (err) {
                resp.send("新增时写文件失败!");
            } else {
                //把页面重新加载到学生查询页面
                //新增成功后 页面重定向到查询页面
                resp.redirect("http://localhost:8080/student/query");
            }
        })

    }
    //resp.send("add....");
})

4、修改功能

//跳转到修改页面
router.get("/toUpdate", function (req, resp) {
    let succ = false;
    //取得get提交的请求参数   获取的是你要修改学生的学号
    let params = req.query; //{sno:s001,sname:xxx}
    let sno = params.sno;
    let currentStudentObject = {};
    //根据学号查询datas数组是否存在此学生对象
    for (let i = 0; i < datas.length; i++) {
        if (sno == datas[i].sno) {
            currentStudentObject = datas[i];
            succ = true;
            break;
        }
    }
    if (succ) {
        //把学生对象的数据渲染到修改页面上  {sno:xxx,sname:xxx...}
        resp.render("updatestudent.html", currentStudentObject);
    } else {
        resp.send("该学生不存在,不能修改");
    }

})

//修改功能
router.post("/update", function (req, resp) {
    let succ = false;
    //获取请求参数 
    let params = req.body;
    for (let i = 0; i < datas.length; i++) {
        if (params.sno == datas[i].sno) {
            currentStudentObject = datas[i];
            succ = true;
            break;
        }
    }
    if (succ) {
        let exist = false;
        //执行修改操作
        //先把datas数组更新,把更新好的datas数据写到datas.json文件
        for (let i = 0; i < datas.length; i++) {
            if (params.sno == datas[i].sno) {
                datas[i] = params;
                exist = true;
                break;

            }
        }
        if (exist) {
            //把数组对象转换成json字符串写到文件中
            let resultContent = JSON.stringify(datas, null, 4);
            fs.writeFile(path.join(__dirname, "json", "datas.json"), resultContent, function (err) {
                if (err) {
                    resp.send("修改时写文件失败!");
                } else {
                    //把页面重新加载到学生查询页面
                    //新增成功后 页面重定向到查询页面
                    resp.redirect("http://localhost:8080/student/query");
                }
            })
        }
    } else {
        resp.send("该学生不存在,不能修改");
    }
});

5、删除功能

//删除功能
router.get("/delete",function(req,resp){
    //取得你要删除的学号
    var sno = req.query.sno;
    let succ=false;
    let index;
    for (let i = 0; i < datas.length; i++) {
        if (sno == datas[i].sno) {
            index=i;
            succ = true;
            break;
        }
    }
    if(succ){
        //先把datas.json中的相应学号的数据进行删除,把datas.json进行更新
        datas.splice(index,1);
        //把数组对象转换成json字符串写到文件中
        let resultContent = JSON.stringify(datas, null, 4);
        fs.writeFile(path.join(__dirname, "json", "datas.json"), resultContent, function (err) {
            if (err) {
                resp.send("删除时写文件失败!");
            } else {
                //把页面重新加载到学生查询页面
                //新增成功后 页面重定向到查询页面
                resp.redirect("http://localhost:8080/student/query");
            }
        })
    }else{
        resp.send("该学生不存在,不能删除");
    }
});

studentRouter.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #table1{
            border:1px solid #000;
            border-collapse: collapse;
            width: 500px;
        }

        #table1 th,#table1 td{
            border:1px solid #000;
            height: 30px;
        }
    </style>
    <script type="text/javascript" src="http://localhost:8080/js/jquery-3.4.1.min.js"></script>
    <script type="text/javascript">
        $(function(){
            $("#addBtn").click(function(){
                window.location.href="http://localhost:8080/static/addstudent.html";
            });
        });

        function del(sno){
           var flag =  window.confirm("确实删除此数据吗?");
           if(flag){
            window.location.href="http://localhost:8080/student/delete?sno="+sno;
           }
        }
    </script>
</head>
<!-- {num:xxx ,studentlist:[{},{}]} -->
<body>
    <h1>学生查询页面 总人数:{{num}}</h1>
    <input type="button" value="新增" id="addBtn"/>
    <table id="table1">
        <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>操作</th>
        </tr>
        {{each studentlist}}
        <tr>
            <!--  {{$index}} 获取的是循环的元素的下标-->
            <!--  {{$value}} 获取数组的下标处的对象 {} -->
            <!-- {{$value.sno}} 获取的对象的sno属性名称对应的值 -->
            <!-- <td>{{$index}}-{{$value.sno}}</td> -->
            <td>{{$value.sno}}</td>
            <td>{{$value.sname}}</td>
            <td>{{$value.age}}</td>
            <td>{{$value.sex}}</td>
            <td>
                <a href="http://localhost:8080/student/toUpdate?sno={{$value.sno}}">修改</a>
                &nbsp;
                <a href="javascript:void(0)" onclick="del('{{$value.sno}}')">删除</a>
            </td>
        </tr>
        {{/each}}
       
    </table>
</body>
</html>

datas.json

[
    {
        "sno": "s001",
        "sname": "张三",
        "age": 10,
        "sex": "男"
    },
    {
        "sno": "s002",
        "sname": "李四",
        "age": 20,
        "sex": "女"
    },
    {
        "sno": "s003",
        "sname": "王五",
        "age": 30,
        "sex": "男"
    },
    {
        "sno": "s004",
        "sname": "赵六",
        "age": 23,
        "sex": "男"
    },
    {
        "sno": "s005",
        "sname": "周期",
        "age": 25,
        "sex": "女"
    },
    {
        "sno": "s006",
        "sname": "周期",
        "age": 25,
        "sex": "女"
    },
    {
        "sno": "s009",
        "sname": "小王",
        "age": "20",
        "sex": "女"
    },
    {
        "sno": "s0010",
        "sname": "小李",
        "age": "34",
        "sex": "女"
    }
]

addstudent.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>新增学生信息</h1>
    <form action="http://localhost:8080/student/add" method="post">
        <table>
            <tr>
                <td>学号:</td>
                <td><input type="text" name="sno" id="sno" required="required"></td>
            </tr>
            <tr>
                <td>姓名:</td>
                <td><input type="text" name="sname" id="sname" ></td>
            </tr>
            <tr>
                <td>年龄:</td>
                <td><input type="text" name="age" id="age" ></td>
            </tr>
            <tr>
                <td>性别:</td>
                <td>
                    <input type="radio" name="sex" value="男" checked="checked">男
                    <input type="radio" name="sex" value="女">女
                </td>
            </tr>
            <tr>
                <th  colspan="2">
                    <input type="submit" value="保存">
                    <input type="reset" value="重填">
                </th>
            </tr>
        </table>
    </form>
    
</body>

</html>

updatestudent.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script type="text/javascript" src="http://localhost:8080/js/jquery-3.4.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#queryBtn").click(function () {
                window.location.href = "http://localhost:8080/student/query";
            });
        })
    </script>
</head>

<body>
    <h1>修改学生信息</h1>
    <form action="http://localhost:8080/student/update" method="post">
        <table>
            <tr>
                <td>学号:</td>
                <td><input type="text" name="sno" id="sno" value="{{sno}}"></td>
            </tr>
            <tr>
                <td>姓名:</td>
                <td><input type="text" name="sname" id="sname" value="{{sname}}"></td>
            </tr>
            <tr>
                <td>年龄:</td>
                <td><input type="text" name="age" id="age" value="{{age}}"></td>
            </tr>
            <tr>
                <td>性别:</td>
                <td>
                    {{if sex=='男'}}
                    <input type="radio" name="sex" value="男" checked="checked">男
                    <input type="radio" name="sex" value="女">女
                    {{else if sex=='女'}}
                    <input type="radio" name="sex" value="男">男
                    <input type="radio" name="sex" value="女" checked="checked">女
                    {{/if}}
                </td>
            </tr>
            <tr>
                <th colspan="2">
                    <input type="submit" value="修改">
                    <input type="button" value="查询" id="queryBtn">
                </th>
            </tr>
        </table>
    </form>
</body>

</html>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值