①先创建一个文件夹,自定义名称,
②电脑装有node.js,mongodb
③创建文件夹,shift+右击打开 Powershell窗口
④搭建服务器 npm install express 再npm install mongoose 连接数据库
⑤在node_modules里面有express,mongoose,mongodb文件夹就可以了
⑥app.js要在文件夹的cmd中允许,修改了,或者删除了,都要用Ctrl+c重新进入服务器
代码部分
引用bootstrap4的样式
css:<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
jquery:<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
首页:list.html
<div class="container">
<a href="add.html" class="btn btn-primary" role="button" id="add">添加用户</a>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>用户名</th>
<th>年龄</th>
<th>爱好</th>
<th>邮箱</th>
<th>操作</th>
</tr>
</thead>
<tbody id="infoDOM"></tbody>
</table>
</div>
<script>
//初始化页面调用该函数
render()
//3、给所有的删除按钮点击事件 因为删除节点是用jq动态生成的,故点击事件需要用事件委托
$("#infoDOM").on('click','.del',function(){
let id = $(this).parent().attr('data-id');
//发送请求
$.ajax({
url:'http://localhost:3000/delete?id='+id,
success(result){
if(result){
render()
}else{
alert("删除失败")
}
}
})
})
//4.给修改器按钮加点击事件
$("#infoDOM").on('click','.modify',function(){
let id = $(this).parent().attr('data-id');
location.href = './modify.html?id='+id; //跳转到当前这条数据的修改页面
})
//1.函数功能:向服务器发送请求 获取数据调用dealtr来渲染页面
function render(){
$.ajax({
url:'http://localhost:3000/list',
success(result){
let str = '' //存字符串
result.forEach(item => { //遍历数组
str += dealtr(item); //将取出的数据中的每一项(对象)
});
$("#infoDOM").html(str); //将表格tbodye的内容设置为返回的数据DOM节点 str
}
})
}
//2.功能:封装函数将数据渲染到DOM节点里
//参数: data 数据
//返回值: DOM节点字符串
function dealtr(data){
return`
<tr>
<td>${data.name}</td>
<td>${data.age}</td>
<td>${data.hobbies.join("/")}</td>
<td>${data.email}</td>
<td data-id="${data._id}">
<button type="button" class="btn btn-danger btn-sm del">删除</button>
<button type="button" class="btn btn-success btn-sm modify">修改</button>
</td>
</tr>
`
}
</script>
添加页:add.html
<div class="container">
<h2>添加用户</h2>
<form>
<div class="form-group">
<label for="userName">用户名</label>
<input type="text" class="form-control" id="userName">
</div>
<div class="form-group">
<label for="age">年龄</label>
<input type="number" class="form-control" id="age">
</div>
<div class="form-group">
<label for="email">邮箱</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="hobbies">爱好</label>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" value="足球">足球
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" value="看书">看书
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" value="敲代码">敲代码
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" value="听歌">听歌
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" value="睡觉">睡觉
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" value="钓鱼">钓鱼
</label>
</div>
</div>
<button type="submit" class="btn btn-primary" id="submit">添加用户</button>
</form>
</div>
<script>
//给添加用户的按钮加点击使事件
$("#submit").click(function(e){
e.preventDefault() //阻止表单提交的默认行为
//获取input内的值
let name = $("#userName").val();
let age = $("#age").val();
let email = $("#email").val();
let hobbiesArr = [];
$("[type = 'checkbox']").each(function(index,item){
if($(item).prop('checked')){
hobbiesArr.push($(item).val())
}
})
//要传输给服务器的数据
let obj = {
name,
age,
email,
hobbies:JSON.stringify(hobbiesArr)
}
//发请求访问add路由,将obj作为数据一起发送给服务器,服务器添加成功给客户端返回布尔值true反之false
$.ajax({
url:'http://localhost:3000/add',
type:'post',
data:obj,
success(result){
if(result){
location.href = './list.html'
}else{
alert("添加失败")
}
}
})
})
</script>
修改页:modify.html
<div class="container">
<h2>修改用户信息</h2>
<form>
<div class="form-group">
<label for="userName">用户名</label>
<input type="text" class="form-control" id="userName">
</div>
<div class="form-group">
<label for="age">年龄</label>
<input type="number" class="form-control" id="age">
</div>
<div class="form-group">
<label for="email">邮箱</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="hobbies">爱好</label>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" value="足球">足球
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" value="看书">看书
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" value="敲代码">敲代码
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" value="听歌">听歌
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" value="睡觉">睡觉
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" value="钓鱼">钓鱼
</label>
</div>
</div>
<button type="submit" class="btn btn-primary" id="submit">修改用户</button>
</form>
</div>
<script>
//1.获取当前的数据,渲染在页面里
let id = location.href.split('id=')[1]; //当前数据的id
//console.log(id);
$.ajax({
url:'http://localhost:3000/selectOne?id='+id,
success(result){
let data = result[0]; //数据对象
$("#userName").val(data.name);
$("#age").val(data.age);
$("#email").val(data.email);
let hobbies = data.hobbies;
$('input[type="checkbox"]').each((index,item) =>{
let val = $(item).val();
if(hobbies.includes(val)){
$(item).prop('checked',true)
}
})
}
})
//2.点击修改时再将修改后的数据存进去
$("#submit").click(function(e){
e.preventDefault();
//获取input内的值
let name = $("#userName").val();
let age = $("#age").val();
let email = $("#email").val();
let hobbiesArr = [];
$("[type = 'checkbox']").each(function(index,item){
if($(item).prop('checked')){
hobbiesArr.push($(item).val())
}
})
//要传输给服务器的数据
let obj = {
id,
name,
age,
email,
hobbies:JSON.stringify(hobbiesArr)
}
//发请求访问add路由,将obj作为数据一起发送给服务器,服务器添加成功给客户端返回布尔值true反之false
$.ajax({
url:'http://localhost:3000/modify',
type:'post',
data:obj,
success(result){
if(result){
location.href = './list.html'
}else{
alert("修改失败")
}
}
})
})
</script>
数据部分:app.js
//引入模块
const express = require("express")
const mongooes = require("mongoose")
//链接数据库
mongooes.connect('mongodb://localhost/user',{useNewUrlParser:true,useUnifiedTopology:true})
.then(()=>{console.log("user的数据库连接成功")})
.catch((err)=>{console.log(err,"user的数据库连接失败")})
//设置集合规则
const userSchema = new mongooes.Schema({
name:{
type:String,
require:true,
minlength:2,
maxlength:5
},
age:{
type:Number,
min:18,
max:80
},
hobbies:[String],
email:String
})
//创建集合
const User = mongooes.model('User',userSchema);
// User.create([
// {
// "name":"赵钱",
// "age":20,
// "hobbies":["足球","篮球","橄榄球"],
// "email":"zhaoqian@126.com"
// },
// {
// "name":"孙李",
// "age":21,
// "hobbies":["吃饭","睡觉","打豆豆"],
// "email":"sunli@126.com"
// },
// {
// "name":"周武",
// "age":33,
// "hobbies":["足球","看书","敲代码"],
// "email":"wuwu@126.com"
// },
// {
// "name":"郑旺",
// "age":41,
// "hobbies":["听歌","广场舞","打豆豆"],
// "email":"wangwang@126.com"
// },
// {
// "name":"王二小",
// "age":50,
// "hobbies":["钓鱼","看球"],
// "email":"wanger@163.com"
// },
// {
// "name":"李麻子",
// "age":71,
// "hobbies":["吃饭","睡觉","看孙女"],
// "email":"356478@qq.com"
// }
// ])
//搭建服务器
const app = express()
//设置允许跨域访问该服务器 ----- 解决list访问时跨域报错的bug
app.all('*',(req,res,next) =>{
res.header("Access-Control-Allow-Origin","*")
next()
})
//post请求消息解析的中间件
app.use(express.urlencoded({extended:false}))
app.use(express.json())
//路由
//获取数据
app.get('/list',(req,res) =>{
User.find().then(result =>{
res.send(result)
})
})
//删除数据
app.get('/delete',(req,res) =>{
let id = req.query.id;
User.findOneAndDelete({_id:id})
.then(result =>{
res.send(true);
})
.catch(err =>{
res.send(false);
})
})
// 添加用户
app.post('/add',(req,res)=>{
// 接收请求发送过来的数据
let newData = req.body;
let hobbies = JSON.parse(newData.hobbies);
let newObj = { //需要插入到数据库中文档
"name":newData.name,
"age":newData.age,
"hobbies":hobbies,
"email":newData.email
}
// 插入到数据库中
User.create(newObj)
.then(result =>{
res.send(true);
})
.catch(err =>{
res.send(false);
})
})
//通过id查询数据
app.get('/selectOne',(req,res) =>{
let id = req.query.id;
User.find({_id:id}).then(result =>{
res.send(result)
}).catch(err=>{
res.send(false);
})
})
//通过id修改数据
app.post('/modify',(req,res) =>{
// 接收请求发送过来的数据
let newData = req.body;
let hobbies = JSON.parse(newData.hobbies);
let newObj = { //需要插入到数据库中文档
"name":newData.name,
"age":newData.age,
"hobbies":hobbies,
"email":newData.email
}
// 修改数据
let id = newData.id;
User.updateOne({_id:id},newObj).then(result =>{
res.send(true)
}).catch(err =>{
res.send(false);
})
})
// 开启服务
app.listen(3000,()=>{
console.log('running.......')
})