nodejs 做一个留言本

2018-11-26  本文已影响0人  pretty_rain

项目名 5.nodejs_day5
model:数据库模块
node_modules:(express、ejs、formidable、mongodb)下载的模块
public:bootstrap的css和js 还有一张用户头像 (自己找文件)
views : messageBoard.ejs 留言页面
3.messageBoard.js : 后台代码控制页面

image.png

model db.js 操作数据库

/**
 * Created by Administrator on 2018/10/11.
 */

var MongoClient = require("mongodb").MongoClient;

var url = "mongodb://localhost:27017/itcast";

/**
 * 打开数据库
 * @param callback  回调函数
 */
function clientMongo(callback){
    MongoClient.connect(url,function(err,client){
        callback(err,client);
    });
}

/**
 * 查询
 * @param mongoTable  集合名称
 * @param paramJSON   查询条件
 * @param C    回调函数
 * @param D    分页参数
 */
exports.findMongo = function(mongoTable,paramJSON,D,C){
    var argm = arguments;
    //打开数据库
    clientMongo(function(err,client){
       
        if(argm.length==4){
            var agrs = D;
            var callback = C;
            var skipnumber = parseInt((agrs.page-1)*agrs.pageSize) || 0;
            var limitnumber = parseInt(agrs.pageSize) || 0;
            var sort = agrs.sort || {};
        }else if(argm.length == 3){
            var callback = D;
            var skipnumber = 0;
            var limitnumber = 0;
            var sort = {};
        }else{
            return;
        }
        if(err){
            callback(err,null);
            return;
        }
       var db = client.db("itcast");
        db.collection(mongoTable).find(paramJSON).skip(skipnumber).limit(limitnumber).sort(sort).toArray(function(err,result){
            callback(err,result);
            client.close();
        })
    })
}
/**
 * 插入一条
 * @param mongoTable 集合名称
 * @param paramJSON  插入数据
 * @param callback   回调函数
 */
exports.insertMongo = function(mongoTable,paramJSON,callback){
       clientMongo(function(err,client){
           var db = client.db("itcast");
           db.collection(mongoTable).insertOne(paramJSON,function(err,result){
               callback(err,result);
               client.close();
           })
       })
}

/**
 * 修改多条
 * @param mongoTable  集合名称
 * @param whereStr    条件
 * @param updateStr   修改字段
 * @param callback    回调函数
 */
exports.updateMogo = function(mongoTable,whereStr,updateStr,callback){
    clientMongo(function(err,client){
        var db = client.db("itcast");
        //要修改的字段内容
        updateStr = {$set:updateStr};
        db.collection(mongoTable).updateMany(whereStr,updateStr,function(err,result){
            callback(err,result);
            client.close();
        })
    })
}
/**
 * 删除多条
 * @param mongoTable
 * @param parasJSON
 * @param callback
 */
exports.removeMongo = function(mongoTable,parasJSON,callback){
    clientMongo(function(err,client){
        var db = client.db('itcast');
        db.collection(mongoTable).deleteMany(parasJSON,function(err,result){
            callback(err,result);
            client.close();
        })
    })
}
/**
 * 获取总条数
 * @param mongoTable
 * @param parasJSON
 * @param callback
 */
exports.findCount = function(mongoTable,parasJSON,callback){
    clientMongo(function(err,client){
        var db = client.db('itcast');
        db.collection(mongoTable).count(parasJSON,function(err,result){
            callback(err,result);
            client.close();
        })
    })
}

views messageBoard.ejs 留言页面



<!DOCTYPE html>
<html lang="zh-CN">
<head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
 <meta name="description" content="">
 <meta name="author" content="">
 <link rel="icon" href="../../favicon.ico">

 <title>小小留言板</title>

 <!-- Bootstrap core CSS -->
 <link href="/css/bootstrap.css" rel="stylesheet">
 <link rel="stylesheet" href="/newtip.css">
 <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
 <!--[if lt IE 9]>
 <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
 <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
 <![endif]-->
</head>

<body>

<!-- Fixed navbar -->
<nav class="navbar navbar-default navbar-fixed-top">
 <div class="container">
  <div class="navbar-header">
   <a class="navbar-brand" href="#">小小留言板</a>
  </div>
 </div>
</nav>

<!-- Begin page content -->
<div class="container" style="padding-top:70px;">
      <form id="formId">
          <div class="form-group">
           <label for="exampleInputEmail1">用户姓名</label>
           <input type="text" class="form-control" id="exampleInputEmail1" placeholder="用户名" name="username">
          </div>
          <div class="form-group">
           <textarea class="form-control" rows="3" name="usercontent" ></textarea>
          </div>

          <botton class="btn btn-default submitclazz">提交</botton>
      </form>
</div>
<div class="container" style="margin-top:50px;">
    <ul class="media-list">
        <li class="media">
            <div class="media-left">
                <a href="#">
                    <img class="media-object" src="/image/headphoto.jpg" alt="..." style="width:70px;">
                </a>
            </div>
            <div class="media-body">
                <h4 class="media-heading"></h4>

            </div>
        </li>
    </ul>
</div>




<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script type="text/javascript">
      var page = 1;
      var pageSize = 2;
      function messages(page,pageSize){
          page = page;
          $.post("/messages",{page:page,pageSize:pageSize},function(data){
              var arrdata = data.result;
              var countpage = data.count%pageSize==0 ? data.count/pageSize : (parseInt(data.count/pageSize) + 1);
              var str = '<nav aria-label="Page navigation"><ul class="pagination">';
              if(page==1){
                  str +='<li class="disabled">'
                      +'<a href="javascript:void(0);" aria-label="Previous">'
                      +'<span aria-hidden="true">&laquo;</span>'
                      +'</a>'
                      +'</li>';
              }else{
                  str +='<li>'
                      +'<a href="javascript:messages('+(page-1)+','+pageSize+');" aria-label="Previous">'
                      +'<span aria-hidden="true">&laquo;</span>'
                      +'</a>'
                      +'</li>';
              }
              if(page-2>=1){
                  for(var i=page-2; i<page;i++){
                      str += '<li><a href="javascript:messages('+i+','+pageSize+');">'+i+'</a></li>';
                  }
              }else{
                  for(var i=1; i<page; i++){
                      str +='<li><a href="javascript:messages('+i+','+pageSize+');">'+i+'</a></li>'
                  }
              }
              str += '<li class="active" ><a href="javascript:messages('+page+','+pageSize+');">'+page+'</a></li>';
              if(page+2<=countpage){
                  for(var i=page+1; i<=page+2; i++){
                      str += '<li><a href="javascript:messages('+i+','+pageSize+');">'+i+'</a></li>';
                  }
              }else{
                  for(var i=page+1; i<=countpage; i++){
                      str += '<li><a href="javascript:messages('+i+','+pageSize+');">'+i+'</a></li>';
                  }
              }
              if(page==countpage){
                  str +='<li class="disabled" >'
                      +'<a href="javascript:void(0);" aria-label="Next">'
                      +'<span aria-hidden="true">&raquo;</span>'
                      +'</a>'
                      +'</li>'
              }else{
                  str +='<li>'
                      +'<a href="javascript:messages('+(page+1)+','+pageSize+')" aria-label="Next">'
                      +'<span aria-hidden="true">&raquo;</span>'
                      +'</a>'
                      +'</li>'
              }
                  str += '</ul>'
                       +'</nav>';

              for(var i in arrdata){
                      str +='<li class="media">'
                          +'<a style="text-decoration:none;font-style:normal;font-weight:100;" data-messageid="'+(arrdata[i]._id).toString()+'" onclick="deletemessage(this)" class="dataId glyphicon glyphicon-remove" aria-hidden="true"></a>'
                          +'<div class="media-left">'
                          +'<a href="#">'
                          +'<img class="media-object" src="/image/headphoto.jpg" alt="..." style="width:70px;">'
                          +'</a>'
                          +'</div>'
                          +'<div class="media-body">'
                          +'<h4 class="media-heading">'+arrdata[i].name+'</h4>'
                          +arrdata[i].content
                          +'</div>'
                          +'</li>';
              }
              $('.media-list').html(str);
          })
      }
      messages(page,pageSize);
     //提交留言
     $(".submitclazz").on("click",function(e){

         if(!!$('input[name="username"]').val() && !!$('textarea[name=usercontent]').val() ){
             $.post("/dopost",$('#formId').serialize(),function(data){
                   messages(page,pageSize);
             })
         }

     })
    //删除留言
    function deletemessage(obj){
         console.log(obj);
         var id = $(obj).attr("data-messageid");
         console.log(id);
           $.get("/deletemessage",{id:id},function(data){
               messages(page,pageSize);
           })
    }
</script>
</body>
</html>

3.messageBoard.js

/**
 * Created by prettyRain on 2018/10/15.
 */
 var express = require('express');
 var app = express();
 var dbmodel = require('./model/db.js');
 var formidable = require('formidable');
 var ObjectID = require('mongodb').ObjectID;
 
 app.use(express.static('./public'));
 app.set("view engine","ejs");
 app.get("/",function(req,res,next){
     res.render("messageBoard",{})
 });
/**
 * 查询留言
 */
app.post("/messages",function(req,res,next){
     var form = new formidable.IncomingForm()
     form.encoding = 'utf-8';
     form.parse(req, function(err, fields, files) {
         if(err){
             next();
             return;
         }
         var page = fields.page;
         var pageSize = fields.pageSize;
         dbmodel.findMongo("message",{},{page:page,pageSize:pageSize,sort:{shijian:-1}},function(err,result){
             dbmodel.findCount("message",{},function(newerr,count){
               if(err || newerr){
                   next();
                   return;
               }
               res.send({result:result,count:count});
             })
         })
 })
})
/**
 * 提交留言
 */
app.post("/dopost",function(req,res,next){
    var form = new formidable.IncomingForm()
    form.encoding = 'utf-8';
    form.parse(req, function(err, fields, files) {
        if (err) {
            next();
            return;
        }
        var username = fields.username;
        var usercontent = fields.usercontent;
        dbmodel.insertMongo("message",{name:username,content:usercontent,shijian:new Date()},function(err,result){
            if(err){
                next();
                return;
            }
            console.log(result.result);
            res.send(result);
        });
        
    });
})
/**
 * 删除
 */
app.get("/deletemessage",function(req,res){
    dbmodel.removeMongo("message",{_id:ObjectID(req.query.id)},function(err,result){
        if(err){
            next();
            return;
        }
        res.send(result);
    })
});
 app.use("/",function(req,res){
     res.render("error",{});
 })
 app.listen(3000);
上一篇下一篇

猜你喜欢

热点阅读