1. 效果展示:
(1)启动MongoDB数据库服务
(2)Node
环境环境中运行app.js
(3)浏览器地址栏输入http://localhost:3000/list
进入 list 界面
(4)可进行简单的增、删、改、查操作
(5)可通过 MongoDB Compass 可视化软件看到数据库的内容
源代码:
(1)各文件相对位置
(2)list.html
<!DOCTYPE html>
<html lang="Zh">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h6>
<a href="add.html" class="btn btn-primary">添加用户</a>
</h6>
<table class="table table-striped table-bordered">
<tr>
<td>用户名</td>
<td>年龄</td>
<td>爱好</td>
<td>邮箱</td>
<td>操作</td>
</tr>
<tr>
<td>张三</td>
<td>20</td>
<td>
<span>游泳</span>
<span>阅读</span>
<span>旅游</span>
</td>
<td>zhangsan@itcast.cn</td>
<td>
<a href="" class="btn btn-danger btn-xs">删除</a>
<a href="" class="btn btn-success btn-xs">修改</a>
</td>
</tr>
</table>
</div>
</body>
</html>
(3)add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3>添加用户</h3>
<form>
<div class="form-group">
<label>用户名</label>
<input type="text" class="form-control" placeholder="请填写用户名">
</div>
<div class="form-group">
<label>密码</label>
<input type="password" class="form-control" placeholder="请输入密码">
</div>
<div class="form-group">
<label>年龄</label>
<input type="text" class="form-control" placeholder="请填写年龄">
</div>
<div class="form-group">
<label>邮箱</label>
<input type="email" class="form-control" placeholder="请填写邮箱">
</div>
<div class="form-group">
<label>请选择爱好</label>
<div>
<label class="checkbox-inline">
<input type="checkbox" value="足球"> 足球
</label>
<label class="checkbox-inline">
<input type="checkbox" value="篮球"> 篮球
</label>
<label class="checkbox-inline">
<input type="checkbox" value="羽毛球"> 羽毛球
</label>
<label class="checkbox-inline">
<input type="checkbox" value="阅读"> 阅读
</label>
<label class="checkbox-inline">
<input type="checkbox" value="旅游"> 旅游
</label>
<label class="checkbox-inline">
<input type="checkbox" value="观影"> 观影
</label>
<label class="checkbox-inline">
<input type="checkbox" value="逛街"> 逛街
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">添加用户</button>
</form>
</div>
</body>
</html>
(4)index.js
const mongoose = require('mongoose');
// 数据库连接 27017是MongoDB数据库的默认端口
// { useNewUrlParser: true, useUnifiedTopology: true }是根据警告信息添加上的参数
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('数据库连接成功!'))
.catch(() => console.log('数据库连接失败'));
(5)user.js
const mongoose = require('mongoose');
// 创建用户集合规则
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 20
},
age: {
type: Number,
min: 1,
max: 120
},
password: String,
email: String,
// 爱好是以数组形式保存,但可以不只有一个
hobbies: [String]
});
// 创建集合,返回集合构造函数
const User = mongoose.model('User', UserSchema);
module.exports = User;
(6)app.js
const http = require('http');
const url = require('url');
const querystring = require('querystring');
require('./model/index.js');
const User = require('./model/user');
// 创建服务器
const app = http.createServer();
// 为服务器对象添加请求事件
app.on('request', async(req, res) => {
// 获取请求方式
const method = req.method; // req.method返回的方式都是大写的
// 对象解构 获取请求地址; query里保存了ID,true:query字符串转化为对象
const { pathname, query } = url.parse(req.url, true); // url.parse(req.url) 返回一个对象
if (method == 'GET') {
// 呈现添加用户列表页面
if (pathname == '/list') {
// 查询用户信息 users是一个数组
let users = await User.find();
// list页面内容存放在模版字符串``中
// 存放静态部分1
let list = `
<!DOCTYPE html>
<html lang="Zh">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h6>
<a href="/add" class="btn btn-primary">添加用户</a>
</h6>
<table class="table table-striped table-bordered">
<tr>
<td>用户名</td>
<td>年龄</td>
<td>爱好</td>
<td>邮箱</td>
<td>操作</td>
</tr>
`;
// 对数据进行循环拼接,这里的item是每个对象
users.forEach(item => {
list += `
<tr>
<td>${item.name}</td>
<td>${item.age}</td>
<td>`;
// item.hobbies是个数组
item.hobbies.forEach(item => {
// 这里的item是数组中的值
list += `<span>${item} </span>`
});
list += ` </td>
<td>${item.email}</td>
<td>
<a href="/remove?id=${item._id}" class="btn btn-danger btn-xs">删除</a>
<a href="/modify?id=${item._id}" class="btn btn-success btn-xs">修改</a>
</td>
</tr>`;
});
// 存放静态部分1
list += `
</table>
</div>
</body>
</html>
`;
res.end(list);
} else if (pathname == '/add') {
// 呈现用户列表页面
let add = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3>添加用户</h3>
<form method="post" action="/add">
<div class="form-group">
<label>用户名</label>
<input name="name" type="text" class="form-control" placeholder="请填写用户名">
</div>
<div class="form-group">
<label>密码</label>
<input name="password" type="password" class="form-control" placeholder="请输入密码">
</div>
<div class="form-group">
<label>年龄</label>
<input name="age" type="text" class="form-control" placeholder="请填写年龄">
</div>
<div class="form-group">
<label>邮箱</label>
<input name="email" type="email" class="form-control" placeholder="请填写邮箱">
</div>
<div class="form-group">
<label>请选择爱好</label>
<div>
<label class="checkbox-inline">
<input type="checkbox" value="足球" name="hobbies"> 足球
</label>
<label class="checkbox-inline">
<input type="checkbox" value="篮球" name="hobbies"> 篮球
</label>
<label class="checkbox-inline">
<input type="checkbox" value="羽毛球 name="hobbies""> 羽毛球
</label>
<label class="checkbox-inline">
<input type="checkbox" value="阅读 name="hobbies""> 阅读
</label>
<label class="checkbox-inline">
<input type="checkbox" value="旅游" name="hobbies"> 旅游
</label>
<label class="checkbox-inline">
<input type="checkbox" value="观影" name="hobbies"> 观影
</label>
<label class="checkbox-inline">
<input type="checkbox" value="逛街" name="hobbies"> 逛街
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">添加用户</button>
</form>
</div>
</body>
</html>
`;
res.end(add);
} else if (pathname == '/modify') {
let user = await User.findOne({ _id: query.id });
let hobbies = ['足球', '篮球', '羽毛球', '阅读', '旅游', '观影', '逛街'];
// console.log(user);
// 呈现修改用户列表页面
let modify = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3>修改用户</h3>
<form method="post" action="/modify?id=${user._id}">
<div class="form-group">
<label>用户名</label>
<input value="${user.name}" name="name" type="text" class="form-control" placeholder="请填写用户名">
</div>
<div class="form-group">
<label>密码</label>
<input value="${user.password}" name="password" type="password" class="form-control" placeholder="请输入密码">
</div>
<div class="form-group">
<label>年龄</label>
<input value="${user.age}" name="age" type="text" class="form-control" placeholder="请填写年龄">
</div>
<div class="form-group">
<label>邮箱</label>
<input value="${user.email}" name="email" type="email" class="form-control" placeholder="请填写邮箱">
</div>
<div class="form-group">
<label>请选择爱好</label>
<div>
`;
hobbies.forEach(item => {
// 判断当前循环项是否在用户的爱好数组里
if (user.hobbies.includes(item)) {
modify += `
<label class="checkbox-inline">
<input type="checkbox" value="${item}" name="hobbies" checked> ${item}
</label>
`;
} else {
modify += `
<label class="checkbox-inline">
<input type="checkbox" value="${item}" name="hobbies"> ${item}
</label>
`;
}
});
modify += `
</div>
</div>
<button type="submit" class="btn btn-primary">修改用户</button>
</form>
</div>
</body>
</html>
`;
res.end(modify);
} else if (pathname == '/remove') {
// res.end(query.id);
await User.findOneAndDelete({ _id: query.id });
res.writeHead(301, {
Location: '/list'
});
res.end();
}
} else if (method == 'POST') {
// 添加用户功能
if (pathname == '/add') {
// 接受用户提交的信息
// 拼接post参数,一步一步接收
let formData = '';
req.on('data', param => {
formData += param;
});
// post参数接收完毕
req.on('end', async() => {
// console.log(querystring.parse(formData));
// 将字符串转化为对象的形式
let user = querystring.parse(formData);
// 将用户提交的信息添加到数据库中
await User.create(user);
// 301代表重定向,提交成功后跳转页面
// Location: 跳转的地址
res.writeHead(301, {
Location: '/list'
});
res.end();
});
} else if (pathname == '/modify') {
// 接受用户提交的信息
// 拼接post参数,一步一步接收
let formData = '';
req.on('data', param => {
formData += param;
});
// post参数接收完毕
req.on('end', async() => {
// console.log(querystring.parse(formData));
// 将字符串转化为对象的形式
let user = querystring.parse(formData);
// 将用户修改的信息添加到数据库中
await User.updateOne({ _id: query.id }, user);
// 301代表重定向,提交成功后跳转页面
// Location: 跳转的地址
res.writeHead(301, {
Location: '/list'
});
res.end();
});
}
}
});
// 监听端口
app.listen(3000);
console.log('网站服务器启动成功...');