先把代码放在这里,有空在详细说一下
原料/工具:
- Node.js
- MongoDB数据库
- mongoose第三方模块
APP.js代码:
const http = require('http');
const mongoose = require('mongoose');
const url = require('url');
const querystring = require('querystring');
const app = http.createServer();
mongoose.connect('mongodb://127.0.0.1/playground', { useNewUrlParser: true, useUnifiedTopology: true })
.then((result) => {
console.log('数据库连接成功')
})
.catch(() => { console.log("数据库连接失败") });
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 10
},
age: {
type: Number,
min: 10,
max: 80
},
password: String,
email: String,
hobbies: [String]
});
const User = mongoose.model('User', userSchema);
app.on('request', async (req, res) => {
//为服务器添加请求事件
//req.on('request', async (result,err)=>{});
//请求方法
const method = req.method;
//请求地址
const { pathname, query } = url.parse(req.url, true);
if (method == 'GET') {
if (pathname == '/list' || pathname == '/') {
//await只能在异步函数里面被使用
let Users = await User.find();
let list = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/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>
`;
Users.forEach((item) => {
list += `
<tr>
<td>${item.name}</td>
<td>${item.age}</td>
<td>
`;
item.hobbies.forEach(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>
`
});
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/[email protected]/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 name="hobbies" type="checkbox" value="足球"> 足球
</label>
<label class="checkbox-inline">
<input name="hobbies" type="checkbox" value="篮球"> 篮球
</label>
<label class="checkbox-inline">
<input name="hobbies" type="checkbox" value="橄榄球"> 橄榄球
</label>
<label class="checkbox-inline">
<input name="hobbies" type="checkbox" value="敲代码"> 敲代码
</label>
<label class="checkbox-inline">
<input name="hobbies" type="checkbox" value="抽烟"> 抽烟
</label>
<label class="checkbox-inline">
<input name="hobbies" type="checkbox" value="喝酒"> 喝酒
</label>
<label class="checkbox-inline">
<input name="hobbies" type="checkbox" value="烫头"> 烫头
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">添加用户</button>
</form>
</div>
</body>
</html>`;
res.end(add);
} else if (pathname == '/modify') {
let Usermsg = await User.findOne({ _id: query.id });
let hobbies = ['足球', '篮球', '橄榄球', '敲代码', '抽烟', '喝酒', '烫头', '吃饭', '睡觉', '打豆豆'];
console.log(Usermsg);
//呈现修改页面
let modify = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3>修用户</h3>
<form method="POST" action="/modify?id=${Usermsg._id}">
<div class="form-group">
<label>用户名</label>
<input name='name' value="${Usermsg.name}" type="text" class="form-control" placeholder="请填写用户名">
</div>
<div class="form-group">
<label>密码</label>
<input name="password" value="${Usermsg.password}" type="password" class="form-control" placeholder="请输入密码">
</div>
<div class="form-group">
<label>年龄</label>
<input name="age" value="${Usermsg.age}" type="text" class="form-control" placeholder="请填写年龄">
</div>
<div class="form-group">
<label>邮箱</label>
<input name="email" value="${Usermsg.email}" type="email" class="form-control" placeholder="请填写邮箱">
</div>
<div class="form-group">
<label>请选择爱好</label>
<div>
`;
hobbies.forEach(item => {
// 判断当前循环项在不在用户的爱好数据组
let isHobby = Usermsg.hobbies.includes(item);
if (isHobby) {
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'){
await User.findOneAndDelete({_id:query.id});
res.writeHead(301, { Location: '/list' });
res.end();
}
} else if (method == 'POST') {
if (pathname == '/add') {
let fromdata = "";
//接收post参数
req.on('data', param => {
fromdata += param;
});
//post参数接收完毕
req.on('end', async () => {
// console.log(querystring.parse(fromdata));
let user = querystring.parse(fromdata);
await User.create(user);
});
res.writeHead(301, { Location: '/list' });
res.end();
} else if (pathname == '/modify') {
let fromdata = "";
//接收post参数
req.on('data', param => {
fromdata += param;
});
//post参数接收完毕
req.on('end', async () => {
// console.log(querystring.parse(fromdata));
let user = querystring.parse(fromdata);
await User.updateOne({ _id: query.id }, user);
});
res.writeHead(301, { Location: '/list' });
res.end();
}
};
res.end("ok")
});
app.listen(3000);
运行代码,当前文件夹下输入:
node app.js
浏览器访问地址:
localhost:3000
效果图:
用户信息增删改查