目录
在网页中实现数据库增删改查的主要思想
搭建网站服务器,实现客户端与服务器之间的通信
连接数据库,创建用户集合,并向集合中插入文档
当用户访问/list时,会查询所有用户信息
1.实现路由功能
1.呈现用户列表页面
1. 再次单击更改按钮时,用户 ID 将传递到当前页面。
2、从数据库中查询当前用户信息html主页面,并将用户信息显示在页面上
2、从数据库中查询用户信息,并在列表中显示用户信息
1. 指定表格的提交地址和请求形式
2、接受客户端传递过来的变更信息,找到用户,并将用户信息修改为最新的。
拼接用户信息和表格HTML并将拼接结果返回给客户端
当用户访问/add时,呈现表单页面,实现添加用户信息的功能。
当用户访问/modify时,出现更改页面,实现更改用户信息的功能。
当用户访问/delete时,实现用户删除功能。
首先让我们链接我们自己的数据库index.js
// 引入MongoDB
const mongoose = require('mongoose')
// 如果后面插入数据 发现没有该数据库 会自动创建
mongoose.connect('mongodb://localhost/playground', {
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => console.log("数据库连接成功"))
.catch(() => console.log(err, '数据库连接失败'))
为数据库user.js设置一些用户规则
// 即便是两个文件中都引入了mongoose但不会造成性能上的浪费
const mongoose = require('mongoose')
// 创建用户集合规则
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minLength: 2,
maxLength: 20
},
age: {
type: Number,
min: 18,
max: 80
},
password: String,
email: String,
hobbies: [String]
})
// 创建集合 返回集合构造函数
const User = mongoose.model('User', userSchema)
// 将User开放出去 使其他文件 在引入 user.js之后 就可以使用User构造函数了
module.exports = User;
制作一个添加数据的静态网页add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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 value="" name="name" type="text" class="form-control" placeholder="请填写用户名">
</div>
<div class="form-group">
<label>密码</label>
<input value="" 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>
<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>
制作一个主页list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>987654@qq.com</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>
最重要的js代码
const http = require('http')
// 先从当前目录查找 其次从上一层目录查找
const url = require('url')
const querystring = require('querystring')
// 创建服务器
const app = http.createServer()
require('./model/index.js')
const User = require('./model/user')
// 为服务器对象追加事件
app.on('request', async (req, res) => {
// 获取请求方式
const method = req.method
// 请求地址
const {
// query 保存了id 默认字符串类型的 想要让其变为数组类型就 加一个true
pathname,
query
} = url.parse(req.url, true)
if (method === 'GET') {
// 呈现用户信息
if (pathname == '/list') {
// html字符串
let users = await User.find();
console.log(users)
let list = `
用户列表
添加用户
用户名
年龄
爱好
邮箱
操作
`;
users.forEach(item => {
console.log(item);
list += `
${item.name}
${item.age}
`
item.hobbies.forEach(item => {
list += `${item}`;
list += `
`;
})
list += `
${item.email}
<a href = "/remove?id=${item.id}" class = "btn btn-danger btn-xs"> 删除
<a href="/modify?id=${item.id}" class="btn btn-success btn-xs">修改
`
})
list += `
`
res.end(list);
} else if (pathname == '/add') {
let add = `
添加用户
添加用户
`;
res.end(add)
} else if (pathname == "/modify") {
// find方法查询时 返回的都是数组 所以这里用findOne 返回的就是对象了
let user = await User.findOne({
_id: query.id
})
let hobbies = ["足球", "篮球", "篮球", "橄榄球", "敲代码", "吃饭", "睡觉", "打豆豆"]
// console.log(user)
// 呈现修改用户表单页面
let modify = `
添加用户
修改用户
<form method = "post"
action = "/modify?id=${user.id}" >
<input value="${user.name}" name="name" type="text" class="form-control" placeholder="请填写用户名">
<input value ="${user.password}"
name = "password"
type = "password"
class = "form-control"
placeholder = "请输入密码" >
<input value ="${user.age}"
name = "age"
type = "text"
class = "form-control"
placeholder = "请输入年龄" >
<input value ="${user.email}"
name = "email"
type = "email"
class = "form-control"
placeholder = "请输入邮箱" >
`;
hobbies.forEach(item => {
// 判断当前循环项在不在用户的爱好数据中
let isHobby = user.hobbies.includes(item)
if (isHobby) {
modify += `${item}" name="hobbies" checked>${item}
`
} else {
modify += `${item}" name="hobbies">${item}
`
}
})
modify += `
`
res.end(modify)
} else if (pathname == "/remove") {
await User.findOneAndDelete({
_id: query.id
})
res.writeHead(301, {
Location: '/list'
})
res.end();
}
} else if (method === 'POST') {
// 用户添加功能
if (pathname == '/add') {
// 用户添加功能
let formData = '';
req.on('data', param => {
// 接受post参数
formData += param
})
// post参数 接收完毕
req.on('end', async () => {
let user = querystring.parse(formData)
await User.create(user)
// 301代表重定向
// location 表示跳转地址
res.writeHead(301, {
Location: '/list'
})
res.end()
})
} else if (pathname == '/modify') {
// 用户添加功能
let formData = '';
req.on('data', param => {
// 接受post参数
formData += param
})
// post参数 接收完毕
req.on('end', async () => {
let user = querystring.parse(formData)
//修改文档内容
await User.updateOne({
_id: query.id
},
user
)
// 301代表重定向
// location 表示跳转地址
res.writeHead(301, {
Location: '/list'
})
res.end()
})
}
}
})
// 监听端口
app.listen(3000)
自我激励
没有什么可抱怨的。 今天的每一步html主页面,都在为之前的每一个选择付出代价。 每次做一件事的时候,想想以后被打脸会不会疼。