前提安装了mongodb数据库和node.js
需要npm安装的
express
bodyparser//可选 用get就不用 用post就需要
mongodb//可以选用mongoose
根据需求可加上一些简单的cookie-parser 、express-session、md5之类
首先在选定文件夹
npm init -y初始化一些
-y的意思是默认生成不写就自己填相关信息
初始化完可以看见文件夹有
接着安装需要的依赖
有express body-parser mongodb
然后新建一个js文件 引入依赖
const path=require("path")
const express=require("express")
const bodyparser=require("body-parser")
const cookieparser=require("cookie-parser")
const app=express()
const dao=require('./model/dao.js')
const ObjectId=require("mongodb").ObjectID//这个是获取mongodb里面的自动生成的id用
然后简单的编写一下前端页面
我在新建www文件夹下编写前端页面
闲着麻烦没有下载jq包就简单的在网上引用一下资源
下列是我的前端页面index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
<style>
*{
margin: 0;
padding: 0;
list-style: none;
}
table{border-collapse: collapse;}
td{
border:1px solid red;
width: 200px;
line-height: 40px;
text-align: center;
}
.editdiv{
width: 600px;
height: 700px;
border: 1px solid whitesmoke;
position: absolute;
z-index: 3;
background: white;
border-radius: 5px;
box-shadow: 10px 10px 5px 2px silver;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
display: none;
}
.editclose{
font-size: 20px;
color: gray;
right: 5px;
top: 5px;
position: absolute;
text-shadow: 2px 2px 1px silver;
cursor:pointer ;
}
.editclose:hover{
color: red;
}
</style>
</head>
<body>
<input type="text" class="addproname" placeholder="商品名称"/>
<input type="text" class="addprice" placeholder="商品价格" />
<button class="add">添加商品</button>
<table>
<thead>
<tr>
<td>商品编码</td>
<td>商品名称</td>
<td >商品价格</td>
<td>编辑商品</td>
<td>删除商品</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<input type="text" class="findproname" placeholder="商品名称(模糊查询)"/>
<input type="text" class="findprice" placeholder="商品价格(精确查询)" />
<button class="find">查询商品</button>
<div class="editdiv">
<h2>编辑</h2><div class="editclose">X</div></br>
<input type="text" class="editproname" placeholder="商品名称"/>
<input type="text" class="editprice" placeholder="商品价格" />
<button class="edit">确认编辑</button>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
datafind();
})
$(".add").click(()=>{
$.ajax({
type:"post",
url:"http://localhost:3300/adddata",
data:{
proname:$(".addproname").val(),
price:$(".addprice").val()
},
success:function(res){
alert("添加成功")
datafind()
}
})
})
function datafind(p1,p2){
var numb=0
console.log(p1,p2)
$.ajax({
type:"post",
url:"http://localhost:3300/finddata",
data:{
num:numb,
proname:p1,
price:p2
},
success:function(res){
console.log(res)
if(res.length==0){
alert("数据为空")
}
var str=""
for(var i=0;i<res.length;i++){
str+="<tr><td>"+res[i]._id+"</td><td>"+res[i].proname+"</td><td>"+res[i].price+"</td><td class='editdata' οnclick='editdata(this)'>编辑商品</td><td οnclick='deletedata(this)'>删除商品</td></tr>"
$("tbody").html(str)
}
}
})
}
function editdata(a){
$(".editdiv").show()
$(".editproname").val($(a).siblings().eq(1).html())
$(".editprice").val($(a).siblings().eq(2).html())
var pid=$(a).siblings().eq(0).html()
var proname1=$(a).siblings().eq(1).html()
var price1=$(a).siblings().eq(2).html()
console.log(proname1,price1)
$(".edit").click(()=>{
$.ajax({
type:"post",
url:"http://localhost:3300/editdata",
data:{
pronamebefore:proname1,
pricebefore:price1,
pronameafter:$(".editproname").val(),
priceafter:$(".editprice").val(),
_id:pid
},
success:function(res){
alert("编辑成功")
$(".editdiv").hide()
datafind()
}
})
})
}
function deletedata(b){
var p1=$(b).siblings().eq(0).html()
$.ajax({
type:"post",
url:"http://localhost:3300/deletedata",
data:{
_id:p1
},
success:function(res){
alert("删除成功")
datafind()
}
})
}
$(".find").click(()=>{
var p1=$(".findproname").val()
var p2=$(".findprice").val()
datafind(p1,p2)
})
$(".editclose").click(()=>{
$(".editdiv").hide()
})
</script>
</html>
ajax请求到后端 即index.js文件
const path=require("path")
const express=require("express")
const bodyparser=require("body-parser")
const cookieparser=require("cookie-parser")
const app=express()
const dao=require('./model/dao.js')
const ObjectId=require("mongodb").ObjectID
app.use(cookieparser())
app.use(bodyparser.urlencoded({extended:false}))
app.use(bodyparser.json())
app.use('/index',express.static('./www/index.html'));
app.use('/register',express.static('./www/server/register.html'))
app.use('/login',express.static('./www/server/login.html'))
app.all("/*", function(req, res, next) {
// 跨域处理
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next(); // 执行下一个路由
})
app.post('/adddata',function(req,res){
console.log(req.body)
let proobj=req.body
dao.insert(proobj,res,(r)=>{
res.send(r)
})
})
app.post('/finddata',function(req,res){
var num=req.body.num
var proname1=req.body.proname
var price1=req.body.price
if(price1==""){
proobj={proname:proname1}
}else if(proname1==""){
proobj={price:price1}
}else{
proobj={}
}
dao.find(num,proobj,res,(r)=>{
res.send(r)
})
})
app.post('/editdata',function(req,res){
var proobj={_id:new ObjectId(req.body._id)}
var proobj1={proname:req.body.pronameafter,price:req.body.priceafter}
dao.update(proobj,proobj1,res,(r)=>{
res.send(r)
})
})
app.post('/deletedata',function(req,res){
var proobj={_id:new ObjectId(req.body._id)}
dao.remove(proobj,res,(r)=>{
res.send(r)
})
})
app.post('/login',function(req,res){
var seven=req.body.seven
var userobj={username:req.body.username,password:req.body.password}
dao.findUser(userobj,res,(r)=>{
console.log(r)
if(r.length!=0){
res.cookie('token',req.body.username,{maxAge:24*60*60*1000,httpOnly:true});
}
res.send(r)
},userobj)
})
app.post('/register',function(req,res){
var userobj={username:req.body.username}
dao.findUser(userobj,res,(r)=>{
console.log(r)
if(r.length==0){
dao.insertUser(userobj,res,(a)=>{
res.json({states:true,data:"注册成功"})
})
}else{
console.log(33333333)
res.json({states:false,data:"已存在账户"})
}
})
})
//app.use('/index',function(req,res){
// if(req.cookies.token){
// res.redirect('http://localhost:3300/index')
// }else{
// res.redirect('http://localhost:3300/login')
// }
//})
app.use(function(req,res){
if(req.cookies.token){
res.redirect('http://localhost:3300/index')
}else{
res.redirect('http://localhost:3300/login')
}
})
app.listen(3300,function(err,res){
if(err) throw err
console.log("服务器已启动 http://localhost:3300")
})
然后在目录下创建一个封装mongodb各类方法文件
model下的dao.js文件
在这个dao.js文件里面写mongodb连接以及函数
根据你在mongodb数据库里面建的数据库和集合写
以下是dao.js文件
const MongoClient=require("mongodb").MongoClient
const url='mongodb://localhost:27017'
function _connect(callback){
MongoClient.connect(url,{useNewUrlParser: true,useUnifiedTopology: true},function(err,db){
if(err) throw err
callback(db)
})
}
module.exports.find=function(num,proobj,res,callback){
_connect(function(db){
num=parseInt(num)
var dbo=db.db("productions")
dbo.collection("productions").find(proobj).limit(num).toArray(function(err,result){
if(err) throw err
db.close()
callback(result)
})
})
}
module.exports.insert=function(proobj,res,callback){
_connect(function(db){
var dbo=db.db("productions")
if(proobj instanceof Array){
proobj=proobj
}else{
proobj=[proobj]
}
dbo.collection("productions").insertMany(proobj,function(err,r){
if(err) throw err
db.close()
callback(r)
})
})
}
module.exports.update=function(proobj,proobj1,res,callback){
_connect(function(db){
var dbo=db.db("productions")
dbo.collection("productions").update(proobj,{$set:proobj1},function(err,r){
if(err) throw err
db.close()
callback(r)
})
})
}
module.exports.remove=function(proobj,res,callback){
_connect(function(db){
var dbo=db.db("productions")
dbo.collection("productions").remove(proobj,function(err,r){
if(err) throw err
db.close()
callback(r)
})
})
}
module.exports.findUser=function(userobj,res,callback){
_connect(function(db){
var dbo=db.db("prouser")
dbo.collection("userlist").find(userobj).toArray(function(err,r){
if(err) throw err
db.close()
callback(r)
})
})
}
module.exports.insertUser=function(userobj,res,callback){
_connect(function(db){
var dbo=db.db("prouser")
dbo.collection("userlist").insert(userobj,function(err,a){
if(err) throw err
db.close()
callback(a)
})
})
}
登录页面就省的展示了
记得得开启mongodb数据库先
然后在启动