/* cnpm install express ejs body-parser md5 mongoose moment --save
1.搭建服务器
2.引入ejs模板
2.1配置模板类型
2.2配置模板路径
2.3配置静态资源目录
3.配置路由渲染ejs文件
3.1路由模块化--在项目目录day07中新建router文件夹
3.2在router文件夹中新建用户user_router.js文件,内部放置和用户相关的路由配置
3.3配置路由将页面渲染给浏览器
3.4在app.js中引入自定义的路由模块
3.5使用路由自定义模块
4.数据库的操作
4.1在database文件夹中新建db.js文件,连接数据库,之后将db.js引入到app.js中
4.2 在day07文件夹中新建model文件夹--内部放置--集合规则文件
4.3 在对应的路由中引入集合
4.4如果需要提交表单并且是通过post方式提交的,要在app.js中配置body-parser模块
*/
//引入模块
let express = require('express');
let ejs = require('ejs');
let mongoose = require('mongoose');
let bodyParser = require('body-parser');
let userRouter = require('./router/users_router');
require('./database/db');
//搭建服务器
let app = new express();
app.listen(9527, () => {
console.log('9527端口已开启');
});
//解析表单提交的数据
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//引入ejs模板
app.set('view engine', ejs);
app.set('views', __dirname + '/views');
app.use(express.static('public'));
app.use('/admin', userRouter);
admin文件夹下的文件
components文件夹下的公共组件
header.ejs
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a href="" class="navbar-brand">
好谷大神管理系统
a>
div>
div>
nav>
body>
html>
aisdes.ejs
<div class="list-group">
<a href="#" class="list-group-item active">用户管理a>
<a href="/admin/userlist" class="list-group-item">用户列表a>
<a href="/admin/useradd" class="list-group-item">添加用户a>
<a href="#" class="list-group-item">用户分类a>
div>
<div class="list-group">
<a href="#" class="list-group-item active">产品管理a>
<a href="#" class="list-group-item">产品列表a>
<a href="#" class="list-group-item">产品用户a>
<a href="#" class="list-group-item">产品分类a>
div>
users文件夹下的userlist.ejs
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<link rel="stylesheet" href="/css/bootstrap.css">
<script src="/js/jquery-3.6.0.min.js">script>
<script src="/js/bootstrap.js">script>
head>
<body>
<%- include('../components/header.ejs') %>
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<%- include('../components/aside.ejs') %>
div>
<div class="col-md-10">
<div class="row">
<div class="col-md-12">
<ol class="breadcrumb">
<li><a href="#">首页a>li>
<li><a href="#">用户管理a>li>
<li class="active">用户列表li>
ol>
div>
div>
<table class="table table-bordered">
<thead>
<tr>
<th>序号th>
<th>姓名th>
<th>年龄th>
<th>性别th>
<th>邮箱th>
<th>手机号th>
<th>添加日期th>
<th>操作th>
tr>
thead>
<tbody>
<% for(let i=0;i
<tr>
<td><%=(page-1)*size+i+1 %>td>
<td><%=userlists[i].username %>td>
<td><%=userlists[i].age %>td>
<td><%=userlists[i].sex %>td>
<td><%=userlists[i].email %>td>
<td><%=userlists[i].phone %>td>
<td><%=userlists[i].createTime %>td>
<td>
<a href="/admin/useredit?_id=<%=userlists[i]._id %>" class="btn btn-primary">修改a>
<a href="/admin/userdel?_id=<%=userlists[i]._id %>" class="btn btn-danger">删除a>
td>
tr>
<%}%>
tbody>
table>
<div class="row">
<div class="col-md-12">
<nav aria-label="Page navigation">
<ul class="pagination">
<li><a href="#">共有<%= count %>条数据,共有<%= pages %>页a>li>
<li>
<a href="/admin/userlist?page=<%=1%>" aria-label="Previous">
<span aria-hidden="true">首页span>
a>
li>
<li><a href="/admin/userlist?page=<%=page>1?page-1:page=1%>">上一页a>li>
<% for(let j=1;j<=pages;j++){ %>
<li class="<%=page==j?'active':' '%>"><a href="/admin/userlist?page=<%=j%>"><%=j%>a>li>
<% } %>
<li><a href="/admin/userlist?page=<%=page" >下一页a>li>
<li>
<a href="/admin/userlist?page=<%=pages%>" aria-label="Next">
<span aria-hidden="true">尾页span>
a>
li>
ul>
nav>
div>
div>
div>
div>
div>
body>
html>
useradd.ejs
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>添加用户title>
<link rel="stylesheet" href="/css/bootstrap.css">
<script src="/js/jquery-3.6.0.min.js">script>
<script src="/js/jquery-3.6.0.min.js">script>
<script src="/js/bootstrap.js">script>
head>
<body>
<%- include('../components/header.ejs') %>
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<%- include('../components/aside.ejs') %>
div>
<div class="col-md-10">
<div class="row">
<div class="col-md-12">
<ol class="breadcrumb">
<li><a href="#">首页a>li>
<li class="active">添加用户li>
ol>
div>
div>
<form action="http://localhost:9527/admin/douseradd" method="post" enctype="application/x-www-form-urlencoded" style="width: 500px; margin-left: 50px;">
<div class="form-group">
<input type="text" class="form-control" name="username" id="username" placeholder="用户名">
<span class="tips">用户名可用span>
div>
<div class="form-group">
<input type="text" class="form-control" name="pwd" placeholder="密码">
div>
<div class="form-group">
<label for="">
<input type="radio" name="sex" value="男">男
label>
<label for="">
<input type="radio" name="sex" value="女">女
label>
<label for="">
<input type="radio" name="sex" value="保密">保密
label>
div>
<div class="form-group">
<input type="text" class="form-control" name="age" placeholder="年龄">
div>
<div class="form-group">
<input type="text" class="form-control" name="email" placeholder="邮箱">
div>
<div class="form-group">
<input type="text" class="form-control" name="phone" placeholder="手机号">
div>
<div class="form-group ">
<button class="btn btn-default">重置button>
<button class="btn btn-primary" id="subBtn">提交button>
div>
form>
div>
div>
div>
body>
<script>
$(function() {
$('#username').blur(() => {
let username = $('#username').val();
$.ajax({
url: `http://localhost:9527/admin/isusername?username=${username}`,
success: function(result) {
if (result == '1') {
$('.tips').html('用户名已存在').css({ color: 'red' });
$('#subBtn').prop('disabled', 'true');
} else if (result == '0') {
$('.tips').html('用户名可用').css({ color: 'green' });
$('#subBtn').prop('disabled', '');
}
}
})
});
})
script>
html>
useredit.ejs
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>添加用户title>
<link rel="stylesheet" href="/css/bootstrap.css">
<script src="/js/jquery-3.6.0.min.js">script>
<script src="/js/jquery-3.6.0.min.js">script>
<script src="/js/bootstrap.js">script>
head>
<body>
<%- include('../components/header.ejs') %>
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<%- include('../components/aside.ejs') %>
div>
<div class="col-md-10">
<div class="row">
<div class="col-md-12">
<ol class="breadcrumb">
<li><a href="#">首页a>li>
<li class="active">修改用户li>
ol>
div>
div>
<form action="http://localhost:9527/admin/douseredit" method="post" enctype="application/x-www-form-urlencoded" style="width: 500px; margin-left: 50px;">
<div class="form-group">
<input type="text" class="form-control" value="<%= userInfo[0].username%>" name="username" id="username" placeholder="用户名">
<span class="tips">用户名可用span>
div>
<div class="form-group">
<input type="text" class="form-control" name="pwd" placeholder="密码">
div>
<div class="form-group">
<label for="">
>男
label>
<label for="">
>女
label>
<label for="">
>保密
label>
div>
<div class="form-group">
<input type="text" class="form-control" name="age" value="<%= userInfo[0].age%>" placeholder="年龄">
div>
<div class="form-group">
<input type="text" class="form-control" name="email" value="<%= userInfo[0].email%>" placeholder="邮箱">
div>
<div class="form-group">
<input type="text" class="form-control" name="phone" value="<%= userInfo[0].phone%>" placeholder="手机号">
div>
<input type="hidden" name="_id" value="<%= userInfo[0]._id%>">
<div class="form-group ">
<button class="btn btn-default">重置button>
<button class="btn btn-primary" id="subBtn">提交button>
div>
form>
div>
div>
div>
body>
html>
db.js
//引入mongoose
let mongoose = require('mongoose');
//连接数据库
mongoose.connect('mongodb://127.0.0.1:27017/student').then(() => {
console.log('数据库连接成功');
}).catch(err => {
console.log(err);
});
user_model.js
let mongoose = require('mongoose');
//创建规则
let UserRule = new mongoose.Schema({
username: {
type: String,
required: true,
minlength: 2,
maxlength: 20,
trim: true
},
age: {
type: String
},
pwd: {
type: String,
},
sex: {
type: String,
enum: {
values: ["男", "女", "保密"],
message: "请在规定的内容中选取"
}
},
phone: {
type: String
},
email: {
type: String
},
createTime: {
type: String
}
})
//根据规则创建集合
let Users = mongoose.model('Users', UserRule);
//暴露模块
module.exports = {
Users
}
user_router.js
//引入
let express = require('express');
let { Users } = require('../model/users_model');
let md5 = require('md5');
let moment = require('moment');
const { now } = require('mongoose');
//创建一个router对象
let router = express.Router();
//配置用户列表路由--http://localhost:9527/admin/userlist
router.get('/userlist', async (req, res) => {
//分页功能
let { page = 1, size = 4 } = req.query;
let result = await Users.find().skip((page - 1) * size).limit(size);
let count = await Users.find().count();
let pages = Math.ceil(count / size);
res.render('admin/users/userlist.ejs', {
userlists: result, //用户列表
page: Number(page), //当前页
size: Number(size), //每页数据条数
count: count, //总的条数
pages: pages //总的页数
});
});
//配置添加用户路由--http://localhost:9527/admin/useradd
router.get('/useradd', (req, res) => {
res.render('admin/users/useradd.ejs');
});
//点击添加用户界面的按钮通过表单添加数据,将数据提交到--http://localhost:9527/admin/douseradd
router.post('/douseradd', async (req, res) => {
//通过表单添加用户 username age sex pwd email phone address
// douseradd 这个路由要接收到数据,并且存储到数据库中
// post提交的文本数据要通过req.body来获取,要先配置body-parser模块,在app.js中配置
// 添加用户要对密码进行加密 可以使用md5模块
// 添加用户是要定义添加的时间,可以使用moment这个模块格式化时间,先下载 npm install moment --save
// console.log(req.body);
let pwd = md5(req.body.pwd);
let { username, sex, age, email, phone } = req.body;
//monment模块格式化时间
let nowTime = moment().format('YYYY-MM-DD hh:mm:ss');
let result = await Users.create({
username,
sex,
pwd,
email,
age,
phone,
createTime: nowTime
});
//判断result有数据就进行重定向
if (result.username) {
res.redirect('/admin/userlist');
} else {
res.send(``);
}
});
//判断用户是否重复添加
router.get('/isusername', async (req, res) => {
//判断用户名是否存在,如果存在提示用户名已经存在.
//拿着用户输入的username查找数据库
let { username } = req.query;
let result = await Users.find({ username: username });
console.log(result);
if (result.length > 0) {
res.send('1') //存在
} else {
res.send('0') //不存在
}
//之后可以在useradd.ejs下用失去焦点事件验证数据库
});
//配置修改用户路由 http://localhost:9527/admin/useredit
//http://localhost:9527/admin/useredit?_id=6269efbd8ad86076c5d706c0
router.get('/useredit', async (req, res) => {
//将用户的信息写在修改页面
let { _id } = req.query;
let result = await Users.find({ _id: _id });
console.log(result);
res.render('admin/users/useredit.ejs', {
userInfo: result
});
});
//用户修改按钮提交的路由
router.post('/douseredit', async (req, res) => {
let pwd = md5(req.body.pwd);
let { username, sex, age, email, phone, _id } = req.body;
//monment模块格式化时间
let nowTime = moment().format('YYYY-MM-DD hh:mm:ss');
console.log('---');
console.log(req.body);
//修改数据
let result = await Users.updateOne({ _id: _id }, {
username,
sex,
age,
email,
phone,
createTime: nowTime
});
//判断添加成功之后重定向
if (result.modifiedCount == 1) {
res.redirect('/admin/userlist');
} else {
res.send(``);
}
});
//用户点击删除按钮之后的路由
router.get('/userdel', async (req, res) => {
//用户删除
let { _id } = req.query;
let result = await Users.findByIdAndDelete({ _id: _id });
//判断删除成功后重定向
if (result._id) {
res.redirect('/admin/userlist');
} else {
res.send(``);
}
});
//导出router
module.exports = router;
// 该路由文件主要是渲染和用户相关的ejs模板文件
// 模板文件分为前端文件和后端文件
// 如
// 在views中新建admin文件夹放置后端ejs模板文件
// 在views中新建cms文件夹放置前端文件
// 跟用户有关的模板day07-->views-->admin-->users
// 在users文件中新建模板文件
// 登录 login.ejs
// 注册 register.ejs
// 用户列表 userlist.ejs
// 添加用户 useradd.ejs
// 修改用户 useredit.ejs
// 根据用户名模糊查询页面 usersearch.ejs
// 配置路由将建好的页面渲染处理
// 登录 login.ejs 对应路由 http://localhost:9527/admin/login
// 注册 register.ejs 对应路由 http://localhost:9527/admin/register
// 用户列表 userlist.ejs 对应路由 http://localhost:9527/admin/userlist
// 添加用户 useradd.ejs 对应路由 http://localhost:9527/admin/useradd
// 修改用户 useredit.ejs 对应路由 http://localhost:9527/admin/useredit
// 根据用户名模糊查询页面 usersearch.ejs 对应路由 http://localhost:9527/admin/usersearch
下载地址点这里