美文网首页
nodejs图书管理系统

nodejs图书管理系统

作者: 进击的大东 | 来源:发表于2019-04-27 09:54 被阅读0次

nodejs图书管理系统

项目准备工作

安装相关包
  • 创建index.js入口文件

  • 使用npm init -y初始化项目

  • 安装express、art-template、body-parse模块:npm install express art-template body-parser --save

  • 安装单独包:npm install express-art-template --save

初始化入口文件、数据、路由等

入口文件
  • 导入相关包

    <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n18" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">/*
    图书管理系统入口文件
    */
    const express=require('express');
    const router=require('./router.js');
    const template=require('art-template');
    const bodyParser=require('body-parser');
    const app=express();</pre>

  • 设置模板引擎

    <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n22" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">//设置模板引擎
    app.set('views',path.join(__dirname,'views'));
    app.set('view engine','art');
    app.engine('art', require('express-art-template'));
    ​</pre>

  • 请求参数的处理

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n28" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">//处理请求参数
      //挂载参数处理中间件
      app.use(bodyParser.urlencoded({extended:false}));
      //处理json格式的参数
      app.use(bodyParser.json());</pre>
  • 启动服务器功能

    • 配置路由app.use(router);

    • 监听端口

      • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n39" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">app.listen(3000,()=>{
        console.log('running...');
        });</pre>
模拟数据
  • 创建data.json

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n46" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">[{
      "id":"1",
      "name":"三国演义",
      "author":"罗贯中",
      "category":"文学",
      "desc":"一个群雄争霸的年代"
      },
      {
      "id":"2",
      "name":"西游记",
      "author":"吴承恩",
      "category":"文学",
      "desc":"讲诉司徒四人历经磨难西天取经的故事"
      },
      {
      "id":"3",
      "name":"红楼梦",
      "author":"曹雪芹",
      "category":"文学",
      "desc":"封建王朝下一个大家族衰落的故事"
      },
      {
      "id":"4",
      "name":"水浒传",
      "author":"施耐庵",
      "category":"文学",
      "desc":"讲述了108条好汉被逼上梁山起义的故事"
      }
      ]</pre>
路由
  • 把路由绑定到业务层router.js

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n53" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">/*
      路由模块
      */
      const express=require('express');
      const router=express.Router();
      const service=require('./service.js');
      //路由处理,把路由绑定到业务上
      router.get('/',service.showIndex);

      module.exports=router;</pre>
  • 业务层把数据渲染到页面service.js

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n58" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">/*
      业务模块
      */
      const data=require('./data.json');
      //渲染主页面
      exports.showIndex=(req,res)=>{
      res.render('index',{list:data});
      }</pre>

使用模拟数据实现添加图书、修改图书和删除图书

添加图书
  • 在index页面的添加按钮上修改跳转路径toAddBook

  • 在router.js中设置跳转添加图书页面以及添加图书后数据保存的路径

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n68" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">//添加图书,跳转到修改图书的页面
      router.get('/toAddBook',service.toAddBook);
      //添加图书,提交表单
      router.post('/addBook',service.addBook);</pre>
  • 在service.js中实现业务逻辑

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n73" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">//跳转添加图书的页面
      exports.toAddBook=(req,res)=>{
      res.render('addBook',{});
      }
      //修改图书提交表单
      exports.addBook=(req,res)=>{
      //获取表单提交的数据
      let info=req.body;
      let book={};
      for(let key in info){
      book[key]=info[key];
      }
      book.id=maxBookCode()+1;
      data.push(book);
      //把内存中的数据写入文件
      fs.writeFile(path.join(__dirname,'data.json'),JSON.stringify(data),(err)=>{
      if(err){
      res.send('server error');
      }
      //文件写入成功重新跳转到主页面
      res.redirect('/');
      });
      }</pre>
修改图书
  • 在index页面的条目上设置修改图书的跳转路径

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n80" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;"><td><a href="/toEditBook?id={{$value.id}}">修改</a>| <a href="#">删除</a></td></pre>
  • 在router.js中设置修改图书路径

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n85" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">//跳转到编辑图书的页面
      router.get('/toEditBook',service.toEditBook);
      //编辑之后提交表单
      router.post('/editBook',service.editBook);
      module.exports=router;</pre>
  • 在service.js中写业务逻辑代码

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n90" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">//跳转修改图书页面
      exports.toEditBook=(req,res)=>{
      let id=req.query.id;
      let book=null;
      //需要把当前书籍的id传递到页面
      data.forEach((item)=>{
      if(id==item.id){
      book=item;
      return;
      }
      });
      res.render('editBook',book);
      }
      //编辑图书提交数据
      exports.editBook=(req,res)=>{
      let info=req.body;
      data.forEach((item)=>{
      if(info.id==item.id){
      for(let key in info){
      item[key]=info[key];
      }
      return;
      }
      });
      //把内存中的数据写入文件
      fs.writeFile(path.join(__dirname,'data.json'),JSON.stringify(data),(err)=>{
      if(err){
      res.send('server error');
      }
      //文件写入成功重新跳转到主页面
      res.redirect('/');
      });
      }</pre>
删除图书
  • 在index中指定条目删除路径

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n97" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;"><a href="/deleteBook?id={{$value.id}}">删除</a></pre>
  • 在router.js中设置路径

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n102" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">router.get('/deleteBook',service.deleteBook);</pre>
  • 在service.js中实现删除逻辑

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n107" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">//删除图书
      exports.deleteBook=(req,res)=>{
      let id=req.query.id;
      let book=null;
      data.forEach((item)=>{
      if(id==item.id){
      book=item;
      data.pop(book);
      }
      });
      fs.writeFile(path.join(__dirname,'data.json'),JSON.stringify(data),(err)=>{
      if(err){
      res.send('server error');
      }
      //文件写入成功重新跳转到主页面
      res.redirect('/');
      });
      }</pre>
测试修改和添加图书功能

数据库操作与restful接口

数据库的连接与操作

连接数据库
  • 下载数据库模块

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n123" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">npm install mysql --save</pre>
  • 创建数据库并添加模拟数据

  • 封装数据库操作模块db.js

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n136" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">/*
      封装数据库操作通用api
      */
      //加载数据库驱动
      var mysql = require('mysql');
      exports.base=(sql,data,callback)=>{
      var connection = mysql.createConnection({
      // host : '192.168.133.128',
      host:'localhost',
      user : 'root',
      password : '123456',
      database : 'book'
      });
      //执行连接操作
      connection.connect();
      //操作数据库
      connection.query(sql,data, function (error, results, fields) {
      if (error) throw error;
      callback(results);
      });
      //关闭数据库连接
      connection.end();
      }</pre>
  • 修改service业务层接口为restful风格,并从数据库获取数据,操作数据库

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n145" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">/*
      业务模块
      */
      const data=require('./data.json');
      const path=require('path');
      const fs=require('fs');
      const db=require('./db.js');
      //自动生成图书编号,自增
      let maxBookCode=()=>{
      let arr=[];
      data.forEach((item)=>{
      arr.push(item.id);
      });
      return Math.max.apply(null,arr);
      }
      //渲染主页面
      exports.allBooks=(req,res)=>{
      let sql='select * from book';
      db.base(sql,null,(result)=>{
      res.json(result);
      });
      }
      //跳转添加图书的页面
      // exports.toAddBook=(req,res)=>{
      // res.render('addBook',{});
      // }
      //添加图书提交表单
      exports.addBook=(req,res)=>{
      //获取表单提交的数据
      let info=req.body;
      let sql='insert into book set ?';
      console.log('添加图书');
      db.base(sql,info,(result)=>{
      if(result.affectedRows==1){
      res.json({flag:1});
      }else{
      res.json({flag:2});
      }
      });
      }

      //跳转修改图书页面
      exports.getBookById=(req,res)=>{
      let id=req.params.id;
      let sql='select * from book where id=?';
      let data=[id];
      db.base(sql,data,(result)=>{
      res.json(result[0]);
      });
      }
      //编辑图书提交数据
      exports.editBook=(req,res)=>{
      let info=req.body;
      let sql='update book set name=?,author=?,category=?,description=? where id=?';
      let data=[info.name,info.author,info.category,info.description,info.id];
      db.base(sql,data,(result)=>{
      if(result.affectedRows==1){
      res.json({flag:1});
      }else{
      res.json({flag:2});
      }
      })
      }
      //删除图书
      exports.deleteBook=(req,res)=>{
      let id=req.params.id;
      let sql='delete from book where id=?';
      let data=[id];
      db.base(sql,data,(result)=>{
      if(result.affectedRows==1){
      res.json({flag:1});
      }else{
      res.json({flag:2});
      }
      })
      }</pre>
  • 在页面执行数据库操作实现功能

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n154" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;"><!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <title>图书管理系统</title>
      <link rel="stylesheet" type="text/css" href="/www/css/style.css">
      <script type="text/javascript" src="/www/js/jquery.js"></script>
      <script type="text/javascript" src="/www/js/template-web.js"></script>
      <script type="text/javascript" src="/www/js/dialog.js"></script>
      <script type="text/javascript" src="/www/js/index.js"></script>
      <script type="text/template" id="indexTpl">
      {{each list}}
      <tr>
      <td>{{value.id}}</td> <td>{{value.name}}</td>
      <td>{{value.author}}</td> <td>{{value.category}}</td>
      <td>{{$value.description}}</td>
      <td><a href="javascript:;">修改</a>| <a href="javascript:;">删除</a></td>
      </tr>
      {{/each}}
      </script>
      </head>
      <body>
      <div class="title">图书管理系统<a id="addBookId" href="javascript:;">添加图书</a></div>
      <div class="content">
      <table cellpadding="0" cellspacing="0">
      <thead>
      <tr>
      <th>编号</th>
      <th>名称</th>
      <th>作者</th>
      <th>分类</th>
      <th>描述</th>
      <th>操作</th>
      </tr>
      </thead>
      <tbody id="dataList">

      </tbody>
      </table>
      </div>
      <form class="form" id="addBookForm">
      <input type="hidden" name="id">
      名称: <input type="text" name="name">

      作者: <input type="text" name="author">

      分类: <input type="text" name="category">

      描述: <input type="text" name="description">

      <input type="button" value="提交">
      </form>
      </body>
      </html></pre>

    • <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n158" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: inherit; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit;">(function () { function initList() { //渲染列表数据.ajax({
      type:'get',
      url:'/books',
      dataType:'json',
      success:function(data) {
      var html=template('indexTpl',{list:data});
      ('#dataList').html(html); //必须在渲染完成之后操作dom('#dataList').find('tr').each(function(index,element) {
      var td=(element).find('td:eq(5)'); var id=(element).find('td:eq(0)').text();
      //绑定编辑图书的单击事件
      td.find('a:eq(0)').click(function() {
      editBook(id);
      });
      //绑定删除图书的单击事件
      td.find('a:eq(1)').click(function() {
      // console.log(2);
      deleteBook(id);
      });
      //绑定添加图书的单击事件
      addBook();
      var form=('#addBookForm'); form.get(0).reset(); form.find('input[type=hidden]').val(''); }); } }); } initList(); ​ //编辑图书信息 function editBook(id) { var form=('#addBookForm');
      //先根据是数据id查询最新数据
      .ajax({ type:'get', url:'/books/book/'+id, dataType:'json', success:function(data) { //初始化弹窗 var mark=new MarkBox(600,400,'编辑图书',form.get(0)); mark.init(); //填充表单数据 form.find('input[name=id]').val(data.id); form.find('input[name=name]').val(data.name); form.find('input[name=author]').val(data.author); form.find('input[name=category]').val(data.category); form.find('input[name=description]').val(data.description); //对表单提交按钮重新绑定单击事件 form.find('input[type=button]').unbind('click').click(function() { //编辑完成数据后提交表单.ajax({
      type:'put',
      url:'/books/book',
      data:form.serialize(),
      dataType:'json',
      success:function (data) {
      if(data.flag=='1'){
      mark.close();
      initList();
      }
      }
      });
      });
      }
      });
      }

      //删除图书信息
      function deleteBook(id) {
      //先根据是数据id查询最新数据
      .ajax({ type:'get', url:'/books/book/'+id, dataType:'json', success:function(data) { //初始化弹窗 //对表单提交按钮重新绑定单击事件 //编辑完成数据后提交表单.ajax({
      type:'delete',
      url:'/books/book/'+id,
      dataType:'json',
      success:function (data) {
      initList();
      }
      });
      }
      });
      }
      function addBook() {
      // body...
      //添加图书信息
      ('#addBookId').click(function() { var form=('#addBookForm');
      var mark=new MarkBox(600,400,'添加图书',form.get(0));
      mark.init();
      form.find('input[type=button]').unbind('click').click(function() {
      $.ajax({
      type:'post',
      url:'/books/book',
      data: form.serialize(),
      dataType:'json',
      success:function(data) {
      if(data.flag=='1'){
      //添加成功后关闭弹窗重新加载数据
      mark.close();
      initList();
      }
      }
      });
      })
      });
      }

      });</pre>

测试基于数据库的图书管理

github代码下载

相关文章

网友评论

      本文标题:nodejs图书管理系统

      本文链接:https://www.haomeiwen.com/subject/hjehnqtx.html