nodejs写一个后台管理系统

时间:2022-09-19 19:15:18

准备工作

1,全局安装 npm i express -g

2,全局安装 npm i express-generator -g (用express脚手架)

3,脚手架创建项目 express -e  project name(项目名称  列如 project  会生成一系列的目录结构)

4,安装package.json 中的依赖,进入项目列表,安装依赖 npm i   (出现node_modules)

(端口号自动生成在 bin 文件夹下面的.www的文件中 var port=~~~~~)

5,在package.json文件的“scripts”中配置和当前项目相关的所有指令(用 npm run + "script" 中配置的指令启动项目)

6,在package.json文件的“scripts”中配置   "dev": "supervisor ./bin/www"  

7,运行此项目  npm run dev 就行了

8,分页处理时,用到异步  async   安装   npm i async -D

9,以下所有的index.js 中都要引入

1 var express = require('express');
2 var router = express.Router();
3 var mongodb=require('mongodb').MongoClient;
4 
5 var db_str='mongodb://localhost:27017/test';
6 
7 var ObjectId = require('mongodb').ObjectId;
8 
9 var async=require('async');

 

 

10,在以下所有的users.js中都要引入

 1 var express = require('express');
 2 
 3 var router = express.Router();
 4 
 5 var mongodb=require('mongodb').MongoClient;
 6 
 7 var db_str='mongodb://localhost:27017/test';
 8 
 9 var upload=require('./upload');
10 
11 var ObjectId = require('mongodb').ObjectId;

 

 

关于上传数据  textarea的 实现图片的上传,和   富文本编辑器

0,全局安装 npm  i  multiparty -D

1,将xheditor文件和fwb.js放在public下面的js中,

1   $('#con').xheditor({         
2 
3  })      //$("#con")要与textarea的id保持一致

 

2,将unload放在routes下面,

3,在public里面的img中建立一个upload文件夹 

4,在相应的文件中引入

1 <script src="/javascripts/xheditor/xheditor-1.2.2.min.js" type="text/javascript" charset="utf-8"></script>
2 <script src="/javascripts/xheditor/xheditor_lang/zh-cn.js" type="text/javascript" charset="utf-8"></script>

 

5,在根目录下创建一个uploadtem文件夹

6,在users.js引入

1 var upload=require('./upload');
2 router.post('/uploadImg',(req,res)=>{
3         upload(req,res);
4 })

 

7,并且在textarea加class="xheditor"

 

 

 

 

 

 

//注册  

//在view文件夹中创建一个register.ejs

 

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    
    <script src="/javascripts/jquery-1.11.0.js" type="text/javascript" charset="utf-8"></script>
    <script src="/javascripts/bootstrap.min.js" type="text/javascript" charset="utf-8"></script>
    <link rel="stylesheet" type="text/css" href="/stylesheets/bootstrap.min.css"/>
  </head>
 	<style type="text/css">
 		*{
 			margin: 0;
 			padding:0;
 		}
 		body{
 			background-image: url(/images/2.jpg) ; 
 			position: relative;		
 		}
 		h2{
 			position: absolute;
 			color:pink;
 			right:490px;
 			top:20px
 		}
 		h5{
 			position: absolute;
 			right:200px;
 			top:100px;
 			color:yellowgreen
 		}
 		#form{
 			position: absolute;
 			right: 200px;
 			border:1px solid pink ;
 			width:300px;
 			height:400px;
 			top:150px;
 			
 		}
 		.form-group:nth-child(1){
 			position: absolute;
 			top:100px;
 			right:30px;
 		}
 		.form-group:nth-child(2){
 			position: absolute;
 			top:200px;
 			right:30px;
 		}
 		.btn-default{
 			position: absolute;
 			top:300px;
 			right: 100px;
 		}
 		#show,#unshow{
 			width:200px;
 			height:50px;
 			font-size:20px ;
 			text-align: center;
 			line-height: 50px;
 		
 			background: pink;
 			color: #fff;
 			position: absolute;
 			top:350px;
 			left:97px;
 			display:none;
 			border-radius: 20px;
 		}
 	
 		
 	</style>
 	
 </style>
  <body>
  	<h2>请注册</h2>
  	<h5>已有账号,点击<a href="/login">登录</a></h5>
    <div class="form-inline" id="form">
		  <div class="form-group">
		    <label for="exampleInputName2">用户名</label>
		    <input type="text" class="form-control" id="username" >
		  </div>
		  <div class="form-group">
		    <label for="exampleInputEmail2">密码</label>
		    <input type="password" class="form-control" id="password" >
		  </div>
		  <button  class="btn btn-default">注册</button>
		  <div id="show">恭喜你,注册成功</div>
		  <div id="unshow">此用户已存在</div>
		  
		</div>	
		
  </body>
  <script type="text/javascript">
  	$(".btn-default").click(function(){
  		$.ajax({
  			type:"post",
  			url:"/users/register",
  			async:true,
  			data:{
  				username:$("#username").val(),
  				password:$("#password").val()
  			},
  			success:function(data){
  				console.log(data);
  				if(data==1){  					
  					$("#show").slideToggle("show");
  					setTimeout(function(){
  						location.href="/login"
  					},1000)
  					
  				}else{
  					$("#unshow").slideToggle("show");
  				}
  			}
  		});
  	})
  </script>
</html>

 

  

 

 

 

 

 

 在index.js中对注册页面进行渲染

router.get('/register', function(req, res) {
  res.render('register', {});
});

 

 在users.js中对注册页面进行  相同的用户名不能重复注册

//注册
router.post('/register',(req,res)=>{
	mongodb.connect(db_str,(err,database)=>{
		database.collection('user',(err,coll)=>{                                    //有user表插入数据,没有则创建一个user的数据表
			coll.find({'username':req.body.username}).toArray((err,data)=>{   //判断前端传来的username,查找数据表中是否存在
				//console.log(data);
				if(data.length==0){  //如果不存在,则查找出来的data.length==0,表示没有重复注册
					coll.insertOne(req.body,()=>{
						res.send('1');   //插入成功,则向前端send一个“1”
					});
				}else{
					res.send('2'); //用户名已存在,不能重复注册,向前端发送一个‘2’
				}
			})
		})
	})
})

  

//登录

//在view文件夹中创建一个login.ejs文件

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    
    <script src="/javascripts/jquery-1.11.0.js" type="text/javascript" charset="utf-8"></script>
    <script src="/javascripts/bootstrap.min.js" type="text/javascript" charset="utf-8"></script>
    <link rel="stylesheet" type="text/css" href="/stylesheets/bootstrap.min.css"/>
  </head>
 	<style type="text/css">
 		*{
 			margin: 0;
 			padding:0;
 		}
 		body{
 			background-image: url(/images/6.jpg) ; 
 			position: relative;		
 		}
 		h2{
 			position: absolute;
 			color:pink;
 			right:490px;
 			top:20px
 		}
 		h5{
 			position: absolute;
 			right:200px;
 			top:100px;
 			color:yellowgreen
 		}
 		#form{
 			position: absolute;
 			right: 200px;
 			border:1px solid pink ;
 			width:300px;
 			height:400px;
 			top:150px;
 			
 			
 		}
 		.form-group:nth-child(1){
 			position: absolute;
 			top:100px;
 			right:30px;
 		
 		}
 		.form-group:nth-child(2){
 			position: absolute;
 			top:200px;
 			right:30px;
 		
 		}
 		.btn-default{
 			position: absolute;
 			top:300px;
 			right: 100px;
 		}
 		#show,#unshow{
 			width:200px;
 			height:50px;
 			font-size:20px ;
 			text-align: center;
 			line-height: 50px;
 		
 			background: pink;
 			color: #fff;
 			position: absolute;
 			top:350px;
 			left:97px;
 			display:none;
 			border-radius: 20px;
 		}
 	</style>
 	
 </style>
  <body>
  	<h2>欢迎登录</h2>
  	<h5>无账号,点击<a href="/register">注册</a></h5>
    <div class="form-inline" id="form">
		  <div class="form-group">
		    <label for="exampleInputName2">用户名</label>
		    <input type="text" class="form-control" id="username" >
		  </div>
		  <div class="form-group">
		    <label for="exampleInputEmail2">密码</label>
		    <input type="password" class="form-control" id="password" >
		  </div>
		  <button  class="btn btn-default">登录</button>
		  <div id="show">恭喜你,登录成功</div>
		  <div id="unshow">此用户不存在</div>
		  
		</div>	
		
  </body>
  <script type="text/javascript">
  	$(".btn-default").click(function(){
  		$.ajax({
  			type:"post",
  			url:"/users/login",
  			async:true,
  			data:{
  				username:$("#username").val(),
  				password:$("#password").val()
  			},
  			success:function(data){
  				if(data==1){
  					//alert("成功")
  					$("#show").slideToggle("show");
  					setTimeout(function(){
  						location.href='/'
  					},1000)
  					
  				}else{
  					//alert('失败')
  					$("#unshow").slideToggle("show");
  					setTimeout(function(){
  						location.href='/login'
  					},1000)
  					
  				}
  			}
  		});
  	})
  	
  
  </script>
</html>

  

 

存用户名用到express-session,只要存一下用户名在其他页面就能使用

安装依赖 npm i express-session -D

在app.js中配置

var session=require('express-session');

app.use(session({ 
	 secret: 'recommend 128 bytes random string', 
	cookie: { maxAge: 20 * 60 * 1000 },
	resave: true,
	saveUnintialized: true
}))

 //首页(简单的页面布局,在插入数据页article.js,  详情页  detail.js,   修改数据 updata.js  查询数据seek.js )

在已有的文件中书写(index.ejs)

 

 

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
    <link rel="stylesheet" type="text/css" href="/stylesheets/bootstrap.min.css"/>
    <script src="/javascripts/bootstrap.min.js" type="text/javascript" charset="utf-8"></script>
  	<style type="text/css">
  		*{
  			margin:0 ;
  			padding:0;
  		}
  		body{
  			padding:0;
  		}
  		.wrapbox{
  			height:100%;	
  		
  		}
  		.box{
  			width:1583px;
  			height: 786px;
  			margin: 0 auto;
  		}
  		
  		.ttop{
  	
  			width:1583px;
  			height:100px;
  			margin: 0 auto;  		
  			font:italic bold 50px arial,sans-serif;
  			float: right;
  			text-align: center;
  			line-height: 100px;
  			color:skyblue;
  			background: darkslategray;

	 		}
  		h2{
  			margin: 0;
  			font:italic bold 35px arial,sans-serif; 
  						
  		}
  		button{  				
  				margin: 37px 35px;
  				text-align: center;
  				background: darkslategray;
  				color:skyblue;
  				border: none;
  				width:200px;
  				height:50px;
  				display: flex;
  				padding-left: 70px;
  				
  				
  		}
  		button:hover{
  			background: skyblue;
  			color:darkslategray;
  		}
  		.img{
  		
  			position: absolute;
  			right: 8px;
  			top:100px;
  			
  		}
  		img{
  			display: inline-block;
  			width:1300px;
  			height:685px;
  		}
  		
  	</style>
  </head>
  <body>
  	<div class="wrapbox">
  		<div class="box">
  			
  			<div class="ttop">网站后台管理系统</div>
	  		<div class="top">
	  			<h2>welcome:<%- names %></h2>
	  			<button onclick="location.href='/register'">注册</button>
	  			<button onclick="location.href='/login'">登录</button>
	  			<button onclick="location.href='/relogin'">注销</button>//当按注销按钮时页面跳转
	  			<button onclick="location.href='/article'">发表文章</button>
	  			<button >详细信息</button>
	  			<button>联系我们</button>
	  			<button>关于我们</button>
  			</div>	
  			<div class='img'><img src="/images/v.jpg"/></div>
	  	</div>
	  	
	  	
		</div>
  	
    
  </body>
</html>

 

  

 //在index.js对首页进行渲染,并把在login登录页面存的uasername取出来

router.get('/', function(req, res, next) {
  res.render('index', { names:req.session.name });
});

 

 

在首页有一个注销的按钮,当按注销钮时,实现页面跳转,让其跳转到登录页面,(页面跳转的一种写法   res.redirect(''   ''))    在index.js中进行渲染

 1 //注销在
 2 router.get('/relogin',(req,res)=>{
 3   req.session.destroy(function(err){
 4       //res.redirect("/")        
 5         if(err){            
 6             console.log(err)        
 7         }else{            
 8             res.redirect("login")        
 9         }    
10     })
11 });

插入数据及按发表文章按钮

 

在view文件夹下创建一个文件article.ejs

  1 <!DOCTYPE html>
  2 <html>
  3   <head>
  4     <title></title>
  5     
  6     <script src="/javascripts/jquery-1.11.0.js" type="text/javascript" charset="utf-8"></script>
  7     <script src="/javascripts/bootstrap.min.js" type="text/javascript" charset="utf-8"></script>
  8     <link rel="stylesheet" type="text/css" href="/stylesheets/bootstrap.min.css"/>
  9     <script src="/javascripts/xheditor/xheditor-1.2.2.min.js" type="text/javascript" charset="utf-8"></script>
 10       <script src="/javascripts/xheditor/xheditor_lang/zh-cn.js" type="text/javascript" charset="utf-8"></script>
 11   
 12   </head>
 13   <style type="text/css">
 14   
 15           .top{
 16           width:1600px;
 17           height:100px;
 18           background:darkslategray;
 19           margin-bottom: 30px;
 20       }
 21       .top button{                  
 22                   margin: 43px 35px;
 23                   text-align: center;
 24                   background: darkslategray;
 25                   color:skyblue;
 26                   border: none;
 27                   width:200px;
 28                   height:50px;
 29                   display: flex;
 30                   padding-left: 70px;
 31                   
 32                   
 33           }
 34           button:hover{
 35               background: skyblue;
 36               color:darkslategray;
 37           }
 38           h2{
 39               margin: 0;
 40               padding-left: 100px;             
 41               font:italic bold 50px arial,sans-serif;
 42               display: inline-block;
 43               padding-top:25px ;
 44               color:skyblue;
 45               margin-left: 500px;
 46               
 47                   
 48           }
 49           .table{
 50               margin-left: 260px;
 51               width:1340px;
 52               height:100%;
 53           }
 54           #form{
 55               margin-bottom: 50px;
 56               margin-left: 200px;
 57           }
 58           .pagination{
 59               margin-left: 650px;
 60           }
 61           .form-group{
 62               margin-left:50px ;
 63           }
 64           #tit{
 65               width:300px;
 66               
 67           }
 68           
 69           
 70           .btn-danger{
 71               margin-left: 50px;
 72           }
 73           #txt{
 74               float: right;
 75               margin-right:50px ;
 76               margin-bottom: 50px;
 77           }
 78           
 79       </style>     
 80   <body>
 81       <div class="top">
 82           <h2>welcome to 花瓣网</h2>          
 83            <button onclick="location.href='/register'">注册</button>
 84           <button onclick="location.href='/login'">登录</button>
 85           <button onclick="location.href='/relogin'">注销</button>
 86           <button onclick="location.href='/article'">发表文章</button>
 87           <button >详细信息</button>    
 88           <button>联系我们</button>
 89           <button>关于我们</button>
 90       </div>
 91       <div class="form-inline" id="form">
 92           <div class="form-group">
 93             <label for="exampleInputName2">标题</label>
 94             <input type="text" class="form-control" id="tit" >
 95           </div>
 96           <div class="form-group">
 97             <label for="exampleInputEmail2">内容</label>
 98            
 99             <textarea name="" rows="2" cols="80" class="form-control xheditor" id="con" ></textarea>
100         
101           </div>
102           <button  class="btn-danger">发布</button>         
103         </div>    
104         <div id="txt">
105             <input type="text" class="ipt"/>
106             <button id="btn">查询</button>
107         </div>
108         <table class="table">
109             <tr>
110                 <th>序号</th>
111                 <th>标题</th>                
112                 <th>内容</th>
113                 <th>删除</th>
114                 <th>修改</th>
115             </tr>
116             <% data.map(function(item,i){ %>            
117                 <tr>
118                     <td><%- (pageNum-1)*7+i+1 %></td>
119                     <td><a href="/detail?id=<%- item._id %>"><%- item.title%></a></td>
120                     <td><%- item.content%></td>
121                     <td><button class="btn-default" onclick="location.href='/delete?id=<%- item._id %>'">删除</button></td> 
122                     <td><button class="btn-default" onclick="location.href='/updata?id=<%- item._id %>'">修改</button></td>
123                     
124                 </tr>
125             <% }) %>            
126         </table>
127     <nav aria-label="Page navigation">//分页
128   <ul class="pagination">
129     <li>
130       <a href="/article?pageNum=<%- pageNum<=1?1:parseInt(pageNum)-1%>" aria-label="Previous">
131         <span aria-hidden="true">上一页</span>
132       </a>
133     </li>
134     <%if(page >4){%>
135         <li><a href="/article?pageNum=1">1</a></li>
136         <li><a href="/article?pageNum=2">2</a></li>
137         <li><a href="#">...</a></li>   
138         <li><a href="/article?pageNum=<%- page-1 %>"><%- page-1 %></a></li>
139         <li><a href="/article?pageNum=<%- page %>"><%- page %></a></li>
140         
141        <%}else{%>
142            <%for(let i=0;i<page;i++){%>
143             <li><a href="/article?pageNum=<%- i+1 %>"><%-i+1 %></a></li>
144         <%}%>
145            
146       <%}%>
147    
148     <li>
149       <a href="/article?pageNum=<%-pageNum>=page ? page : parseInt(pageNum)+1%>" aria-label="Next">
150         <span aria-hidden="true">下一页</span>
151       </a>
152     </li>
153   </ul>
154 </nav>
155         <script src="/javascripts/fwb.js" type="text/javascript" charset="utf-8"></script>
156         
157         
158   <script type="text/javascript">
159       //发布文章
160       $(".btn-danger").click(function(){
161           $.ajax({
162               type:"post",
163               url:"/users/article",
164               async:true,
165               data:{
166                   title:$("#tit").val(),
167                   content:$("#con").val()
168               },
169               success:function(data){
170                   if(data==1){        
171                       location.href='/article'   //插入数据成功,还是跳转到本页面
172                       
173                   }else{
174                       alert('失败')
175                       
176                   }
177               }
178           });
179       })
180       
181  //查询
182  $("#btn").click(function(){
183      var tit=$(".ipt").val()  //查询按钮前面input里面的值 184          $.ajax({
185           type:"post",
186           url:"/users/seek",
187           async:true,
188           data:{
189               val:tit  //向后台传入的数据 190           },
191           success:function(data){
192               console.log(data);
193               if(data=='1'){
194                   location.href="/seek?tit="+tit;
195               }
196           }
197       });     
198  })
199       
200   
201   </script>
202 </html>

 

 先对插入数据发布按钮进行设计

在article.ejs中对发布按钮进行了ajax请求

1,首先在users.js文件中对传入的数据进行处理

 1 router.post('/article',(req,res)=>{
 2     mongodb.connect(db_str,(err,database)=>{
 3         database.collection('article',(err,coll)=>{
 4             if(req.body.title != 0){        //发布文章的标题不能为空        
 5                 coll.save(req.body,(err,data)=>{  //coll中插入数据 ,数据是ajax前端传入的data
 6                     //console.log(req.body);
 7                     res.send('1');  //插入成功 向前端send一个 ‘1’  (在success中)
 8                     database.close();
 9                 })
10             }
11             
12         })
13     })
14 })

2,再次对插入的数据在index.js进行渲染,显示在前端(对插入的数据进行分页处理)

 1 //发布文章
 2 router.get('/article',(req,res)=>{
 3     mongodb.connect(db_str,(err,database)=>{
 4         database.collection('article',(err,coll)=>{
 5             var pageNum=req.query.pageNum;
 6             pageNum=pageNum?pageNum :1;
 7             //页数
 8             var page=0;
 9             //总数量
10             var count=0;
11             //每页展示的数量
12             var size=7;
13             async.series([          
14                 function(callback){
15                     coll.find({}).toArray((err,data)=>{
16                         count=data.length;
17                         page=Math.ceil(count/size);
18                         //下一页
19                         pageNum=pageNum<=1?1:pageNum;
20                         //上一页
21                         pageNum=pageNum>=page?page:pageNum
22                     })
23                     callback(null,'')
24                 },
25                 function(callback){
26                     coll.find({}).sort({_id:-1}).limit(size).skip((pageNum-1)*size).toArray((err,data)=>{   //sort({_id:-1})按发表的时间排序,新发表的数据在第一行 27                         callback(null,data)
28                     })
29                     
30                 }
31             ],function(err,data){
32                 res.render('article',{data:data[1],page:page,count:count,pageNum:pageNum})
33                 database.close();
34             })
35         })
36     })
37 })

 

 然后修改数据进行设计 

1,首先在view文件夹下创建一个文件updata.ejs

  1 <!DOCTYPE html>
  2 <html>
  3   <head>
  4     <title></title>
  5     
  6     <script src="/javascripts/jquery-1.11.0.js" type="text/javascript" charset="utf-8"></script>
  7     <script src="/javascripts/bootstrap.min.js" type="text/javascript" charset="utf-8"></script>
  8     <link rel="stylesheet" type="text/css" href="/stylesheets/bootstrap.min.css"/>
  9     <script src="/javascripts/xheditor/xheditor-1.2.2.min.js" type="text/javascript" charset="utf-8"></script>
 10       <script src="/javascripts/xheditor/xheditor_lang/zh-cn.js" type="text/javascript" charset="utf-8"></script>
 11   
 12   </head>
 13   <style type="text/css">
 14       .top{
 15           width:1600px;
 16           height:100px;
 17           background:darkslategray;
 18           margin-bottom: 30px;
 19       }
 20       .top button{                  
 21                   margin: 43px 35px;
 22                   text-align: center;
 23                   background: darkslategray;
 24                   color:skyblue;
 25                   border: none;
 26                   width:200px;
 27                   height:50px;
 28                   display: flex;
 29                   padding-left: 70px;    
 30           }
 31           button:hover{
 32               background: skyblue;
 33               color:darkslategray;
 34           }
 35           h2{
 36               margin: 0;
 37               padding-left: 100px;             
 38               font:italic bold 50px arial,sans-serif;
 39               display: inline-block;
 40               padding-top:25px ;
 41               color:skyblue;
 42               margin-left: 500px;
 43         }
 44           .table{
 45               margin-left: 260px;
 46               width:1340px;
 47               height:100%;
 48           }
 49           #form{
 50               margin-bottom: 50px;
 51               margin-left: 200px;
 52               display: flex;
 53               flex-direction: column;
 54           }
 55           .pagination{
 56               margin-left: 650px;
 57           }
 58           .form-group{
 59               margin-left:250px ;
 60               margin-top: 100px;
 61           }
 62           #tit{
 63               width:300px;
 64               
 65           }
 66           
 67           
 68           .btn-danger{
 69               margin-top: 50px;
 70               margin-left: 280px;
 71               width:200px;
 72               height:50px;
 73           }
 74           #txt{
 75               float: right;
 76               margin-right:50px ;
 77               margin-bottom: 50px;
 78           }
 79           
 80       </style>     
 81   <body>
 82       <div class="top">
 83           <h2>welcome to 花瓣网</h2>          
 84            <button onclick="location.href='/register'">注册</button>
 85           <button onclick="location.href='/login'">登录</button>
 86           <button onclick="location.href='/relogin'">注销</button>
 87           <button onclick="location.href='/article'">发表文章</button>
 88           <button >详细信息</button>    
 89           <button>联系我们</button>
 90           <button>关于我们</button>
 91       </div>
 92       <div class="form-inline" id="form">
 93           <div class="form-group">
 94             <label for="exampleInputName2">标题</label>
 95             <input type="text" class="form-control" id="tit" value="<%- data4 %>">
 96           </div>
 97           <div class="form-group">
 98             <label for="exampleInputEmail2">内容</label>
 99            
100             <textarea name="" rows="4" cols="100" class="form-control xheditor" id="con" ><%- data3 %></textarea>
101         
102           </div>
103           <button  class="btn-danger" name="<%- id %>">发布</button>   //给一个属性,点击哪个 哪个的id 传到后台,并且渲染的哪个    
104     </div>    
105   <script type="text/javascript">
106       $(".btn-danger").click(function(){
107           $.ajax({
108               type:"post",
109               url:"/users/updata",
110               async:true,
111               data:{
112                   id:$(this).attr('name'),   // 传到users.js 113                   title:$("#tit").val(),
114                   content:$("#con").val()
115               },
116               success:function(data){ 
117                   if(data=="1"){
118                       location.href='/article';//修改成功跳转到插入数据页面 119                   }else{
120                       location.href='/updata'
121                   }
122                   //console.log(data);
123               
124               }
125           });
126       })
127       
128   
129   </script>
130 </html>

 

2在users.js对前台

 1 //修改
 2 
 3 router.post('/updata',(req,res)=>{
 4     mongodb.connect(db_str,(err,database)=>{
 5         database.collection('article',(err,coll)=>{
 6             //console.log(req.body);            
 7             var id=ObjectId(req.body.id)
 8             coll.updateOne({_id:id },{$set:{title:req.body.title,content:req.body.content}},(err,data)=>{   // 修改从前端传入来的id的title,content数据  9             res.send("1")
10             database.close();
11             })
12         })
13     })
14 })

3,在index.js对数据处理

 1 //修改
 2 
 3 
 4 router.get('/updata',(req,res)=>{
 5     var id=ObjectId(req.query.id);
 6     mongodb.connect(db_str,(err,database)=>{
 7         database.collection('article',(err,coll)=>{
 8             coll.find({_id:id}).toArray((err,data)=>{
 9                 //console.log(data);
10                 res.render('updata',{data3:data[0].content,data4:data[0].title,id:data[0]._id});    //把修改过的数据传到前端 11                 database.close();
12             })
13             
14         })
15     })
16 })

 

删除按钮进行处理

1,删除按钮有个跳转路径,我们对其进行渲染   index.js,(无ajax 所以不用在   users.js   进行处理)

//删除
router.get('/delete',(req,res)=>{
    var id=ObjectId(req.query.id);
    mongodb.connect(db_str,(err,database)=>{
        database.collection('article',(err,coll)=>{
            coll.remove({_id:id});
            //console.log(id);
            res.redirect('article')
            database.close();
        })
    })
})

 

查询数据 的详细信息     content  在view文件夹创建一个seek.js文件

 

  1 <!DOCTYPE html>
  2 <html>
  3   <head>
  4     <title></title>
  5     
  6     <script src="/javascripts/jquery-1.11.0.js" type="text/javascript" charset="utf-8"></script>
  7     <script src="/javascripts/bootstrap.min.js" type="text/javascript" charset="utf-8"></script>
  8     <link rel="stylesheet" type="text/css" href="/stylesheets/bootstrap.min.css"/>
  9     <script src="/javascripts/xheditor/xheditor-1.2.2.min.js" type="text/javascript" charset="utf-8"></script>
 10       <script src="/javascripts/xheditor/xheditor_lang/zh-cn.js" type="text/javascript" charset="utf-8"></script>
 11   
 12   </head>
 13   <style type="text/css">
 14   
 15           .top{
 16           width:1600px;
 17           height:100px;
 18           background:darkslategray;
 19           margin-bottom: 30px;
 20       }
 21       .top button{                  
 22                   margin: 43px 35px;
 23                   text-align: center;
 24                   background: darkslategray;
 25                   color:skyblue;
 26                   border: none;
 27                   width:200px;
 28                   height:50px;
 29                   display: flex;
 30                   padding-left: 70px;
 31                   
 32                   
 33           }
 34           button:hover{
 35               background: skyblue;
 36               color:darkslategray;
 37           }
 38           h2{
 39               margin: 0;
 40               padding-left: 100px;             
 41               font:italic bold 50px arial,sans-serif;
 42               display: inline-block;
 43               padding-top:25px ;
 44               color:skyblue;
 45               margin-left: 500px;
 46               
 47                   
 48           }
 49           .table{
 50               margin-left: 260px;
 51               width:1340px;
 52               height:100%;
 53           }
 54           #form{
 55               margin-bottom: 50px;
 56               margin-left: 200px;
 57           }
 58           .pagination{
 59               margin-left: 650px;
 60           }
 61           .form-group{
 62               margin-left:50px ;
 63           }
 64           #tit{
 65               width:300px;
 66               
 67           }
 68           
 69           
 70           .btn-danger{
 71               margin-left: 50px;
 72           }
 73           #txt{
 74               float: right;
 75               margin-right:50px ;
 76               margin-bottom: 50px;
 77           }
 78           
 79       </style>     
 80   <body>
 81       <div class="top">
 82           <h2>welcome to 花瓣网</h2>          
 83            <button onclick="location.href='/register'">注册</button>
 84           <button onclick="location.href='/login'">登录</button>
 85           <button onclick="location.href='/relogin'">注销</button>
 86           <button onclick="location.href='/article'">发表文章</button>
 87           <button >详细信息</button>    
 88           <button>联系我们</button>
 89           <button>关于我们</button>
 90       </div>
 91 <table class="table">
 92             <tr>
 93                 <th>序号</th>
 94                 <th>标题</th>                
 95                 <th>内容</th>
 96                 
 97             </tr>
 98             <% data.map(function(item,i){ %>            
 99                 <tr>
100                     <td><%- i+1%></td>
101                     <td><a href="/detail?id=<%- item._id %>"><%- item.title%></a></td>
102                     <td><%- item.content%></td>                    
103                 </tr>
104             <% }) %>            
105         </table>
106 </html>

 

 

1,在users.js对数据进行处理

 1 //查询
 2 router.post('/seek',(req,res)=>{
 3     mongodb.connect(db_str,(err,database)=>{
 4         database.collection('article',(err,coll)=>{
 5             var tit=new RegExp(req.body.val)   //以从前端传来的input中值的首字母进行查询      
 6             coll.find({content:tit}).toArray((err,data)=>{
 7                 //console.log(data);
 8                 res.send('1');  //查询成功向前端send   ‘1’
 9                 database.close();
10             })
11         })
12     })
13 })

 

 

2,对查询的数据进行渲染,传到前端  users.js

 1 //查询
 2 
 3 router.get('/seek',(req,res)=>{
 4     mongodb.connect(db_str,(err,database)=>{
 5         database.collection('article',(err,coll)=>{
 6             var tit=new RegExp(req.query.tit);
 7             coll.find({content:tit}).toArray((err,data)=>{
 8                 //console.log(data);
 9                 res.render('seek',{data:data});
10                 database.close();
11             })
12         })
13     })
14 })