node.js-curd案例

案例步骤:
1.处理模板
2.配置相关的静态资源(开放给服务器访问的目录)
3.配置模板引擎
4.简单路由:/students渲染静态页面
5.路由设计
6.提取路由

//app.js
var express = require('express');
var fs = require('fs');
var router = require('./router');
//将 post 的body 添加到 url 对象的属性中
var bodyParser = require('body-parser');
var app =  express();
//配置body-parser(中间件),专门用来解析post 的请求体
app.use(bodyParser.urlencoded({ extended : false}));
app.use(bodyParser.json());
//处理页面中各种链接请求,将各种静态资源统一放在一个开头相同的文件中,当服务端收到新的链接请求时,就会到相应目录中去寻找
app.use ('/node_modules',express.static('../node_modules/'));
app.use('/views/',express.static('./views/'));
/*
  配置使用 art-template  模板引擎,第一个参数表示,当渲染以  .art 结尾的文件的时候(也可以修改为其他后缀,如: .html ), 使用
  art-template  模板引擎, express-art-template  是专门用来在 Express 中把art-template 整合到Express 中,原因在于 express-art-template 依赖了 art-template
*/
app.engine('html',require('express-art-template'));
//挂载路由
app.use(router);

app.listen(5000,function(){
    console.log('Running server 5000.....');
})








//router.js
var fs = require('fs');
var url = require('url');
var express = require('express');

//获取封装各种调用函数的文件
var Student = require('./excute');
//创建路由器
var router = express.Router();
//路由容器,用来存放各种各样的路由
   //主页面的views目录要和app.js目录同级
    router.get('/',function(request,response){
    //从文件中读取数据,(因为读取文件时,默认读取格式是16进制)第二个参数是文件传输格式,也可以选择用函数 data.toString()进行转换;
    //500状态码,服务端出错状态码
        Student.FindAll(function(error , students){
            if(error){
                return response.status(500).send('Server error!');
            }else{
                response.render('index.html',{
                   Students: students
                });
            }
        });
    });
        //Save保存学生的函数有两个参数:
        /*
           第一个参数: 包含学生信息的对象
           第二个参数: 处理学生对象的回调函数
       
           回调函数的参数:
            第一个参数: error 参数,读取成功返回null,失败则返回一个对象
            第二个参数:从文件中读出的包含students的data对象
 
        */
    router.post('/add',function(request,response){
        Student.Add(request.body,function(error,Students){
              if(error){
                  return response.render('Failure to add.');
              }else{
                  return response.render('index.html',{
                      Students: Students,
                  });
              }
        });
    });
    /*
       在用户点击编辑后,将相应id的学生信息返回服务端,服务端再渲染给编辑方框进行修改
    */
    router.get('/edit',function(request,response){
        Student.Edit(request.query,function(error,student,Students){
           if(error) {
               return response.render('Edit failure!');
           }
               else{
               //返回单个学生信息,渲染编辑框
               return response.render('index.html',{
                    Sno: student.Sno,
                    Name: student.Name,
                    Age: student.Age,
                    Gender: student.Gender,
                    Female: student.Female,
                    Hobbies: student.Hobbies,
                    Students: Students
               })
               
           }
        });
    });
    /*
        用户修改完毕后,点击Update按钮,更新数据发送给服务端,服务端再重新渲染页面
    */
    router.post('/update',function(request,response){
        Student.Update(request.body,function(error,Students){
            if(error){
                return response.render("Update failure");
            }else{
                return response.render('index.html',{
                      Students: Students
                });
            }
        });
    });
    //删除相应学生的所有信息
    router.get('/delete',function(request,response){
        Student.Delete(request.query,function(error,Students){
            if(error) return response.write('Delete Failure');
            else{
                return response.render('index.html',{
                    Students: Students
                });
            }
        });
    });
    //导出路由容器
    module.exports  = router;



//封装异步编程,执行模块
/*
  操作文件中的数据,只处理数据,不关心业务
*/
// {"students":[{"Sno":"20125011049","Name":"撒旦法","Age":"10000","Gender":"female","Hobbies":"Reap(收割)"},{"Sno":"20125011053","Name":"Vodka","Age":"18","Gender":"male","Hobbies":"666666"},{"Sno":"20202","Name":"YU","Age":"500","Gender":"female","Hobbies":"长寿面"}]}
//返回相应学号学生的信息
function FindSno(Sno,Students){
     for( item in Students){
       if(Students[item].Sno == Sno.id) return(Students[item]);
     }
}
//查重,有重复的就修改到不重复位置为止
function DuplicateChecking(Sno , Students){
    for ( index in Students){
        if(Students[index].Sno == Sno )  Sno++;
    }
    return Sno;
}
//更新相应学号的学生信息,学生的学号不能修改
function Renewal(student,Students){
    console.log(student);
    for( item in Students){
       if(Students[item].Sno == student.Sno){
            Students[item] = student;
       }
    }
    return Students;
}
//删除学生相应信息
function Remove(Sno,Students){
    var calculate = 0;
    for (  var item  = 0; item < Students.length; item++){
        if (Students[item].Sno == Sno.id){
            calculate++;
        }
        Students[item] = Students[item+calculate];
    }
    Students.length -= calculate;
    return Students;
}
const { response } = require('express');
var fs = require('fs');
//默认路径
var DbPath = './database.json';
//获取所有学生列表,这里的形参是一个回调函数,用来获取异步函数 readFile 的data
/*
   callback 的参数是自行定义的,这里定义为
   第一个参数为 error ,第二个参数为一个数组
*/
exports.FindAll = function(callback){
    fs.readFile(DbPath , function(error, data){
        if(error){
            //如果读取文件失败,则通过回调返回一个 error 对象
            return callback(error);
        }else {
            //如果读取成功,则通过回调函数返回解析过得 data 对象中的students 对象
            callback(null,JSON.parse(data).students);
        }
    });
}
//添加保存学生
exports.Add = function(student,callback){
    //Save保存学生的函数有两个参数:
        /*
           第一个参数: 包含学生信息的对象
           第二个参数: 处理学生对象的回调函数
       
           回调函数的参数:
            第一个参数: error 参数,读取成功返回null,失败则返回一个对象
            第二个参数:从文件中读出的包含students的data对象
 
        */
    fs.readFile(DbPath, function(error,data){
        if(error){
            return callback(error);
        }else{ 
                //解析为一个对象
                //将添加的学生后的students对象,转为json格式,再写进文件中
                var students = JSON.parse(data).students;
                student.Sno = DuplicateChecking(student.Sno,students);
                students.push(student);
                var Filedata = JSON.stringify({
                    students: students
                });
                //如果更新后写入失败,则返回写入失败
                //若成功,则返回包含更新后的Students对象的回调结果
                fs.writeFile(DbPath,Filedata,function(error){
                     if(error){
                         return callback(error);
                     }else{
                         callback(null,students);
                       
                     }
                });
        }
    });
}
//编辑学生
exports.Edit = function(Sno,callback){
    fs.readFile(DbPath,function(error,data){
        if(error){
            callback(error);
        }else{
            var Students = JSON.parse(data).students;
            var student = FindSno(Sno,Students);
            callback(error,student,Students);
        }
        
    });
}
//更新学生
exports.Update = function(student,callback){
    fs.readFile(DbPath,function(error,data){
         if(error) callback(error);
         else{
           var Students = JSON.parse(data).students;
           Students = Renewal(student,Students); 
            var Filedata = JSON.stringify({
                students: Students
            });
            fs.writeFile(DbPath,Filedata,function(error){
                if(error) callback(error);
                else{
                   callback(error,Students);
                }
            });
            
         }
    });
}

//删除学生
exports.Delete = function(Sno,callback){
   fs.readFile(DbPath,function(error,data){
       if(error){
           callback(error);
       }else{
           var Students = JSON.parse(data).students;
           Students = Remove(Sno,Students);
           var Filedata = JSON.stringify({
               students: Students
           })
           //将更新后的数据写进文件
           fs.writeFile(DbPath,Filedata,function(error){
               if (error) callback(error);
               else{
                   callback(error,Students);
               }
           });
       }
   });
}


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/views/css/index.css" >
    <title>Index Page</title>
</head>
<body>
    <div id="MajorBody">
        
        <div id ="Header"> 
            <span class="ProjectName"> Student Admini System</span>    
            <input type="text" value="" name ="" placeholder="Search..." class="Search" id="Search" >
            <span class="direct" id="DashBoard">
                <a href="javascript:void(0)">DashBoard</a>
            </span>
            <span class="direct" id="Settings">
                <a href="javascript:void(0)">Settings</a>
            </span>
            <span class="direct" id="Profile">
                <a href="javascript:void(0)">Profile</a>
            </span>
            <span class="direct" id="Help">
                <a href="javascript:void(0)">Help</a>
            </span>
        </div>
 
        <div id="navigator">
            <ul id="Part">
                <li>
                    <a href="#">Overview</a>
                </li>
                
                <li>
                    <a href="#">Overview</a>
                </li>
                
                <li>
                    <a href="#">Overview</a>
                </li>
                
                <li>
                    <a href="#">Overview</a>
                </li>
            </ul>

            <ul id="Part" class="Two">
                <li>
                    <a href="#">Overview</a>
                </li>
                
                <li>
                    <a href="#">Overview</a>
                </li>
                
                <li>
                    <a href="#">Overview</a>
                </li>
                
                <li>
                    <a href="#">Overview</a>
                </li>
            </ul>

            <ul id="Part" class="Three">
                <li>
                    <a href="#">Overview</a>
                </li>
                
                <li>
                    <a href="#">Overview</a>
                </li>
                
                <li>
                    <a href="#">Overview</a>
                </li>
                
                <li>
                    <a href="#">Overview</a>
                </li>
            </ul>
        </div>

        <div id="Board">
            <div id="ProfileBoard">

                <div class="ins">
                    <div class="image">
                        <img src="/views/img/猫咪投降.jpg" alt="">
                    </div>
                    <span class = "Name">Cat</span>
                    <span class = "introduction">Miao~Miao~</span>
                </div>

                <div class="ins">
                    <div class="image">
                        <img src="/views/img/小马嚎叫.jpg" alt="">
                    </div>
                    <span class = "Name">Fang</span>
                    <span class = "introduction">我很强,我知道</span>
                </div>

                <div class="ins">
                    <div class="image">
                        <img src="/views/img/李信.png" alt="">
                    </div>
                    <span class = "Name">Xin</span>
                    <span class = "introduction">不为不存在的天命而压低脊梁</span>
                </div>

                <div class="ins">
                    <div class="image">
                        <img src="/views/img/Yuyuan.jpg" alt="">
                    </div>
                    <span class = "Name">Yuyuan</span>
                    <span class = "introduction">今天吃啥?</span>
                </div>

            </div> 

            
            <form action="" method="POST"  id="ControlButton">
                <!-- 表单元素要带name属性,才可以传输数据 -->
              <!-- 这里的formaction属性可以修改表单的action的值,ie-9以下版本不支持,水~ -->
                <button id="Add" type="submit"  formaction="/add" > Add </button>
                <button id="Update" type = "submit"  formaction="/update" > Update </button>
                
                <input placeholder="Please putin Sno" type="text" id="Sno" name="Sno"   value="{{ Sno }}">
                <input placeholder="Please putin Name" type="text" id="Name" name="Name"  value="{{ Name }}">
                <input placeholder="Please putin Age" type="text" id="Age" name="Age"  value="{{ Age }}">
                <input placeholder="Please putin Gender" type="text" id="Gender" name="Gender"  value="{{ Gender }}">
                <input placeholder="Please putin Hobbies" type="text" id="Hobbies" name="Hobbies"  value="{{ Hobbies }}">
                
            </form>

            <div id="InfoBoard">

                <div class="Title">
                    <div class="Sno">Sno</div>
                    <div class="SName">Name</div>
                    <div class="SAge">Age</div>
                    <div class="SGender">Gender</div>
                    <div class="SHobbies">Hobbies</div>
                </div>
                
                <ul id="Info">
                    {{ each Students}}
                    <li >
                        <div class="Sno"> {{ $value.Sno }}</div>   
                        <div class="SName">{{ $value.Name }}</div>
                        <div class="SAge">{{ $value.Age }}</div>
                        <div class="SGender">{{ $value.Gender }} </div>
                        <div class="SHobbies">{{ $value.Hobbies }}
                            <a href="/edit?id={{$value.Sno}} ">Edit</a>
                            <a href="/delete?id={{$value.Sno}}">Delete</a>
                        </div>
                    </li>
                     {{ /each }}
                </ul>
                
                
            </div>
        </div>

    </div>
</body>
</html> 




--css模块
*{
    margin:0;
    padding: 0;
    box-sizing: border-box;
}
#MajorBody{
   display: flex;
   justify-content: flex-start;
   flex-wrap: wrap;
   width: 1520px;
   height: 1500px;

}

#Header{
   display: flex; 
   justify-content: flex-start;
   align-items: center;
   position:fixed;
   width: 1520px;
   height: 100px;
   color: white;
   background-color: rgba(10, 9, 9, 0.68);
}

.ProjectName{
   padding-left: 10px;
   font-size: 30px;
}

.Search{
   position: relative;
   width: 200px;
   height: 50px;
   margin-left: 450px;
   padding-left: 10px;
   border-radius: 15px;
   border:none;
   outline: none;
   font-size: 25px;
   color:rgba(128, 128, 128, 0.496);
}
.direct{
   display:flex;
   justify-content: flex-start;
   align-items: center;
   width: 120px;
   height: 90px;
}
.direct > a{
   display: inline-flex;
   flex-direction: column;
   justify-content: center;
   align-items: center;
   width: 110px;
   height: 80px;
   font-size: 20px;
   
   text-decoration: none;
   color:aliceblue;
   
}
.direct > a:hover{
   color: aqua;
}
.direct :nth-of-type(1){
   margin-left: 20px;
}
#navigator{
    display: flex;
    flex-direction:column;
    justify-content: flex-start;
    align-items: center;
    width: 200px;
    margin-top: 100px;
    height: 1200px;
    background-color: rgba(194, 218, 240, 0.938);
}

#Part{
   display: flex;
   flex-direction: column;
   justify-content: center;
   align-items: center;
   width: 200px;
   height: 400px;
 
}
#Part > li{
   display: flex;
   justify-content: center;
   align-items: center;
   width:199px;
   height: 70px;
   margin: 3px 5px;
   background-color: rgba(128, 185, 241, 0.442);
}
#Part >li > a{
   display:flex;
   justify-content: flex-start;
   align-items: center;
   width: 100px;
   height: 6px;
   text-decoration: none;
   color: black;
}
#Part >li:hover{
   cursor: pointer;
   background-color: rgba(255, 166, 0, 0.585);
}

#Part > li > a:hover{
   color: white;
}

.Two{
   margin-top: -80px;
}

.Three{
   margin-top: -80px;
}
#Board{
   display: flex;
   justify-content: flex-start;
   flex-wrap: wrap;
   width: 1320px;
   height: 1200px;
   margin-top: 100px;
}

#ProfileBoard{
   display: flex;
   justify-content: flex-start;
   align-items: center;
   width: 1500px;
   height: 300px;
   background-color: rgba(219, 233, 233, 0.755);
}

.ins{
   display:flex;
   justify-content: center;
   align-items:center;
   flex-wrap:wrap;
   width: 300px;
   height: 300px;
   color:rgb(81, 81, 81);
}
.ins > .image> img{
   display:flex;
   width: 150px;
   height: 150px;
   border-radius: 50%;
   
}
.ins .image{
   display:flex;
   justify-content: center;
   align-items: center;
   width: 150px;
   height: 150px;
   border-radius: 50%;
  
}

.ins .Name{
   display: flex;
   justify-content: center;
   align-items: center;
   width: 200px;
   height: 30px;
   margin-top: -20px;
}
.ins .introduction{
   display: flex;
   justify-content: center;
   align-items: center;
   width: 200px;
   height: 50px;
   margin-top: -50px;
}

div[class = "ins"]:nth-child(2){
   margin-left: 30px;
}

div[class = "ins"]:nth-child(3){
   margin-left: 30px;
}
 
div[class = "ins"]:nth-child(4){
   margin-left: 30px;
}
#ControlButton{
   display: flex;
   justify-content: flex-start;
   align-items: center;
   width: 1520px;
   height: 80px;
   background-color: rgba(219, 233, 233, 0.755);
}

#Add{
   display: flex;
   justify-content: center;
   align-items: center;
   margin-left:20px;
   width: 80px;
   height: 60px;
   border-radius: 15px;
   background-color: aqua;
   color:black;
   outline: none;
}
#Update{
   display: flex;
   justify-content: center;
   align-items: center;
   margin-left:20px;
   width: 80px;
   height: 60px;
   border-radius: 15px;
   color: black;
   background-color: red;
   outline: none;
}
#Add:hover{
   color:white;
   cursor: pointer;
}
#Update:hover{
   color:white;
   cursor: pointer;
}
#Sno,#Name,#Gender,#Age,#Hobbies{
   display:flex;
   justify-content: flex-start;
   align-items: center;
   width: 200px;
   height: 40px;
   margin-left: 15px;
   font-size: 15px;
   border-radius: 19px;
   padding-left: 10px; 
   border: 1px rgba(0, 0, 0, 0.517) solid;
   outline:none;
}

#InfoBoard{
   display: flex;
   flex-direction: column;
   justify-content: flex-start;
   flex-wrap:wrap;
   width: 1320px;
   height: 820px;
   background-color: rgba(127, 255, 212, 0.503);
}

.Title{
   display:flex;
   width: 1320px;
   height: 60px;
   justify-content: flex-start;
   align-items: center;
   border-bottom: 2px solid gray;
}

.Sno , .SName , .SGender , .SHobbies , .SAge{
    display:flex;
    justify-content: center;
    align-items: center;
    width: 200px;
    height: 60px;
    border: 1px solid gray;
}

.SHobbies{
   width: 520px;
}
#Info , #Info > li{
   display:flex;
   width: 1320px;
   height: 60px;
   justify-content: flex-start;
   flex-wrap: wrap;
   align-items: center;
   list-style: none;
}
.SHobbies > a {
   display: felx;
   justify-content: flex-start;
   align-items: center;
   text-decoration:none;
   margin-left: 30px;
   color:rgba(0, 0, 255, 0.53);
}
.SHobbies > a:hover{
   cursor:pointer;
   color:red;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值