目录
package.json
后端:
server.js
router/admin/index.js
router/admin/login.js
router/admin/blog.js
router/admin/users.js
router/web/index.js
前端:
views/admin/common/top.ejs
views/admin/index.ejs
views/admin/login.ejs
views/admin/blog.ejs
views/admin/users.ejs
无开发,不安全。
这个小项目用了express框架,ejs模板渲染引擎,调用了mysql的api。
实现了session登录验证,session过期机制,用户和博客文章的CURD操作,上传头像图片的操作。
下面直接贴出代码:
package.json
{"name": "ejs-express-mysql","version": "1.0.0","description": "ejs+express+mysql实现的后台管理","main": "server","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"repository": {"type": "git","url": "git+https://github.com/Nealyang/ejs-express-mysql.git"},"keywords": ["node","express","ejs","mysql"],"author": "Nealyang","license": "ISC","bugs": {"url": "https://github.com/Nealyang/ejs-express-mysql/issues"},"homepage": "https://github.com/Nealyang/ejs-express-mysql#readme","devDependencies": {"body-parser": "^1.16.1","consolidate": "^0.14.5","cookie-parser": "^1.4.3","cookie-session": "^2.0.0-beta.1","ejs": "^2.5.6","express": "^4.18.2","express-router": "0.0.1","express-static": "^1.0.3","multer": "^1.3.0","mysql": "^2.13.0"}
}
后端:
server.js
const express = require('express');
const expressStatic = require('express-static');
const bodyParser = require('body-parser');
const multer = require('multer');
const multerObj = multer({dest:'./static/upload'});
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const consolidate = require('consolidate');
const ejs = require('ejs');//创建服务器
var server = express();
server.listen(4000);//解析请求数据server.use(express.urlencoded({ extended: false }));
server.use(multerObj.any());//设置cookie,session
server.use(cookieParser('Neal_signed'));
(function () {var arr = [];for(var i = 0;i<10000;i++){arr.push('keys_'+Math.random());}server.use(cookieSession({name:'session_id',keys:arr,maxAge:20*60*1000//一般设置20分钟}))
})();//设置模板
server.set('view engine','ejs');
server.set('views','./views');//设置路由
server.use('/admin',require('./router/admin/index')());
server.use('/',require('./router/web/index')());//静态文件的请求
server.use('/files',expressStatic('./static'));
router/admin/index.js
const express = require('express');module.exports = function () {var router = express.Router();router.use(function (req,res,next) {if(!req.session['user_id'] && req.url != '/login'){res.redirect('/admin/login');}else{next();}});router.use('/login',require('./login')());router.use('/blog',require('./blog')());router.use('/users',require('./users')());router.get('/',function (req,res) {res.render('admin/index.ejs');});return router;
};
router/admin/login.js
const express = require('express');
const mysql = require('mysql');
const common = require('../../lib/common');const db = mysql.createPool({host:'localhost',port:3306,user:'root',password:'root',database:'blog'});module.exports = function () {var router = express.Router();router.get('/',function (req,res) {res.render('admin/login.ejs');});router.post('/',function (req,res) {var username = req.body.username;var password = common.md5(req.body.password+common.MD5_SUFFIX);if(username && password){db.query('SELECT * FROM admin_table WHERE username="'+username+'"',function (err,userData) {if(err){console.error(err);res.status(500).send({code:500,data:[],msg:'database error'});}else if(userData.length == 0){res.status(400).send({code:400,data:[],msg:'parameters error'});}else{if(userData[0].password != password){res.status(400).send({code:400,data:[],msg:'username or password error'});}else{req.session['user_id'] = userData[0].ID;//注意这里是在req上面res.status(200).send({code:200,data:[],msg:'success'});}}})}else{res.status(400).send({code:400,data:[],msg:'parameters error'});}});return router;
};
router/admin/blog.js
const express = require('express');
const common = require('../../lib/common');
const mysql = require('mysql');const db = mysql.createPool({host: 'localhost',port: 3306,user: 'root',password: 'root',database: 'blog'
});module.exports = function () {var router = express.Router();router.get('/', function (req, res) {switch (req.query.action) {case 'del'://删除操作db.query('DELETE FROM blog_list_table WHERE id="'+req.query.id+'"',function (err,resultData) {if(err){console.error(err);res.status(500).send({code:500,msg:'database error'});}else{res.redirect('/admin/blog');}});break;case 'mod'://修改操作db.query('SELECT * FROM blog_list_table WHERE id="'+req.query.id+'"',function (err,modData) {if(err){console.error(err);res.status(500).send({code:500,msg:'database error'});}else if(modData.length == 0){res.status(400).send({code:400,msg:'parameters error'});}else{db.query('SELECT * FROM blog_list_table',function (err,allData) {if(err){console.error(err);res.status(500).send({code:500,msg:'database error'});}else{res.render('admin/blog.ejs',{formData:allData,modData:modData});}});}});break;default:db.query('SELECT * FROM blog_list_table', function (err, resultData) {if (err) {console.error(err);res.status(500).send({code: 500, msg: 'database error'}).end();} else {res.render('admin/blog.ejs', {formData: resultData});}});}});router.post('/', function (req, res) {var title = req.body.title.trim();var author = req.body.author.trim();var summary = req.body.summary.trim();var href = req.body.href.trim();if (title && author && summary && href) {if(req.body.modified){//更新操作db.query('UPDATE blog_list_table SET title="'+title+'",author="'+author+'",summary="'+summary+'",href="'+href+'" WHERE ID="'+req.body.modified+'"',function (err,resultData) {if(err){console.error(err);res.status(500).send({code:500,msg:'database error'});}else{res.redirect('/admin/blog');}})}else{//增加操作db.query('INSERT INTO blog_list_table (title,author,summary,href) VALUE("' + title + '","' + author + '","' + summary + '","' + href + '")', function (err, data) {if (err) {console.error(err);res.status(500).send({code: 500, msg: 'database error'}).end();} else {res.redirect('/admin/blog');}});}} else {res.status(400).send({code: 400, msg: 'parameters error'}).end();}});return router;
};
router/admin/users.js
const express = require('express');
const common = require('../../lib/common');
const mysql = require('mysql');
const fs = require('fs');
const pathLib = require('path');const db = mysql.createPool({host: 'localhost',user: 'root',password: 'root',database: 'blog'
});module.exports = function () {var router = express.Router();router.get('/', function (req, res) {switch (req.query.action) {case 'del'://删除操作db.query('SELECT * FROM user_table WHERE ID="' + req.query.id + '"', function (err, queryData) {if (err) {console.error(err);res.status(500).send({code: 500, msg: 'database error'});} else if (queryData.length == 0) {res.status(400).send({code: 400, msg: 'parameters error'});} else {fs.unlink(queryData[0].pic_header.replace('\/files','static'), function (err) {if (err) {console.error(err);res.status(500).send({code:500,msg:'operate err'});} else {db.query('DELETE FROM user_table WHERE ID="'+req.query.id+'"',function (err,resultData) {if(err){console.error(err);res.status(500).send({code: 500, msg: 'database error'});}else{res.redirect('/admin/users');}})}})}});break;case 'mod':db.query('SELECT * FROM user_table',function (err,allData) {if (err) {console.error(err);res.status(500).send({code: 500, msg: 'database error'});} else {db.query('SELECT * FROM user_table WHERE ID="'+req.query.id+'"',function (err,modData) {if (err) {console.error(err);res.status(500).send({code: 500, msg: 'database error'});}else if(modData.length == 0){res.status(400).send({code: 400, msg: 'parameters error'});}else {res.render('admin/users.ejs',{usersData:allData,modData:modData});}});}});break;default:db.query('SELECT * FROM user_table', function (err, allUsersData) {if (err) {console.error(err);res.status(500).send({code: 500, msg: 'database error'});} else {res.render('admin/users.ejs', {usersData: allUsersData});}});}});router.post('/', function (req, res) {var username = req.body.username;var email = req.body.email;if(req.files.length>0){var ext = pathLib.parse(req.files[0].originalname).ext;var pic_header = '/files/upload/' + req.files[0].filename + ext;}//需要进行一些校验,这里就忽略了if(req.body.modified){//修改//查看有没有新传来的头像,如果有,则删除,新建,如果没有,直接更新需要更新的内容if(req.files.length>0){//有修改头像,则进行原来头像的删除,再上传db.query('SELECT * FROM user_table WHERE ID="'+req.body.modified+'"',function (err,modData) {if (err) {console.error(err);res.status(500).send({code: 500, msg: 'database error'});}else if(modData.length == 0){res.status(400).send({code: 400, msg: 'parameters error'});}else{fs.unlink(modData[0].pic_header.replace('\/files','static'),function (err) {if(err){console.error(err);res.status(500).send({code:500,msg:'operate error'});}else{//删除成功,开始对新的文件进行重命名fs.rename(req.files[0].path, req.files[0].path + ext, function (err) {if (err) {console.error(err);res.status(500).send({code: 500, msg: 'operate error'});} else {db.query('UPDATE user_table SET username="'+username+'",email="' + email + '",pic_header="' +pic_header + '" WHERE ID="'+req.body.modified+'"',function (err,data) {if (err) {console.error(err);res.status(500).send({code: 500, msg: 'database error'});}else{res.redirect('/admin/users');}});}});}})}})}else{db.query('UPDATE user_table SET username="'+username+'",email="' + email + '" WHERE ID="'+req.body.modified+'"',function (err,data) {if (err) {console.error(err);res.status(500).send({code: 500, msg: 'database error'});}else{res.redirect('/admin/users');}});}}else{//新增fs.rename(req.files[0].path, req.files[0].path + ext, function (err) {if (err) {console.error(err);res.status(500).send({code: 500, msg: 'data error'});} else {db.query('INSERT INTO user_table (username,email,pic_header) VALUE("' + username + '","' +email + '","' + pic_header + '")', function (err, resultData) {if (err) {console.error(err);res.status(500).send({code: 500, msg: 'database error'});} else {res.redirect('/admin/users');}});}});}});return router;
};
router/web/index.js
const express = require('express');module.exports = function () {var router = express.Router();router.get('/',function (req,res) {res.send('这是前端页面');});return router;
};
前端:
views/admin/common/top.ejs
<!doctype html>
<html lang="utf-8">
<head><meta charset="UTF-8"><title>后台管理-首页</title><link rel="stylesheet" href="/files/admin/css/top.css"><link rel="stylesheet" href="/files/admin/css/reset.css"><script type="text/javascript" src="http://himg2.huanqiu.com/statics/hq2013/js/lib/jquery1.9.1.js"></script><script src="/files/admin/js/top.js"></script>
</head>
<body>
<div class="header"><p>后台管理应用</p><div class="menu"><a href="/admin"><span>首页</span></a><a href="/admin/blog"><span>博文管理</span></a><a href="/admin/users"><span>用户管理</span></a></div>
</div>
</body>
</html>
views/admin/index.ejs
<!doctype html>
<html lang="utf-8">
<head><meta charset="UTF-8"><title>后台管理-首页</title>
</head>
<body>
<% include common/top.ejs%>
<div style="font-size: 32px;font-family: fantasy;padding: 100px 30px 0px;"><p>后台管理主要实现的是:<span style="color: red;">博客的删除修改和新建(涉及到数据的CRUD),以及用户管理(涉及到图片上传).</span></p>
</div>
</body>
</html>
views/admin/login.ejs
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><title>后台管理员登录</title><link rel="stylesheet" href="/files/admin/css/login.css"><link rel="stylesheet" href="/files/admin/css/reset.css"><script type="text/javascript" src="http://himg2.huanqiu.com/statics/hq2013/js/lib/jquery1.9.1.js"></script><script type="text/javascript" src="/files/admin/js/login.js"></script>
</head>
<body>
<div class="login_container"><div class="username_div login_input_container"><img src="/files/admin/img/user_icon.png"><input type="text" autofocus="autofocus" name="username"/></div><div class="password_div login_input_container"><img src="/files/admin/img/password_icon.png"><input type="password" name="password"></div><div class="login_button"></div>
</div>
</body>
</html>
views/admin/blog.ejs
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><title>后台管理-博客管理</title><link rel="stylesheet" href="/files/admin/css/blog.css"><script type="text/javascript" src="http://himg2.huanqiu.com/statics/hq2013/js/lib/jquery1.9.1.js"></script><script src="/files/admin/js/blog.js"></script>
</head>
<body>
<% include common/top.ejs %>
<div class="add_button"><img src="/files/admin/img/add.png">
</div>
<div class="add_form"><img src="/files/admin/img/add.png"><div class="form_bg"></div><form action="?" method="post">标题: <input type="text" name="title" autofocus="autofocus"><br>作者: <input type="text" name="author"><br>摘要: <textarea name="summary"></textarea><br>链接: <input type="text" name="href"><br><input type="submit" value="添加"></form>
</div>
<%if(typeof modData != 'undefined'){%>
<div class="add_form" style="display: flex"><img src="/files/admin/img/add.png"><div class="form_bg"></div><form action="?" method="post"><input type="hidden" name="modified" value="<%= modData[0].ID %>">标题: <input type="text" name="title" autofocus="autofocus" value="<%=modData[0].title%>"><br>作者: <input type="text" name="author" value="<%=modData[0].author%>"><br>摘要: <textarea name="summary"><%=modData[0].summary%></textarea><br>链接: <input type="text" name="href" value="<%=modData[0].href%>"><br><input type="submit" value="确认修改"></form>
</div>
<%}%>
<table><tr><th class="id">ID</th><th class="title">标题</th><th class="author">作者</th><th class="summary">摘要</th><th class="href">链接</th><th class="operation">操作</th></tr><% for(var i = 0;i<formData.length;i++){%><tr><td><%=formData[i].ID%></td><td><%=formData[i].title%></td><td><%=formData[i].author%></td><td><%=formData[i].summary%></td><td><%=formData[i].href%></td><td><a href="?action=del&id=<%=formData[i].ID%>" onclick="return confirm('确定删除?')"><button>删除</button></a><a href="?action=mod&id=<%=formData[i].ID%>"><button>修改</button></a></td></tr><%}%>
</table>
</body>
</html>
views/admin/users.ejs
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><title>后台管理-用户管理</title><link rel="stylesheet" href="/files/admin/css/users.css"><script type="text/javascript" src="http://himg2.huanqiu.com/statics/hq2013/js/lib/jquery1.9.1.js"></script><script src="/files/admin/js/users.js"></script>
</head>
<body>
<% include common/top.ejs%>
<div class="add_button"><img src="/files/admin/img/add.png">
</div>
<div class="add_form"><img src="/files/admin/img/add.png"><div class="form_bg"></div><form action="?" method="post" enctype="multipart/form-data">用户名: <input type="text" name="username" autofocus="autofocus"><br>邮箱: <input type="email" name="email"><br>头像: <input type="file" name="pic_header"><br><input type="submit" value="添加"></form>
</div>
<%if(typeof modData != 'undefined'){%>
<div class="add_form" style="display: flex"><img src="/files/admin/img/add.png"><div class="form_bg"></div><form action="?" method="post" enctype="multipart/form-data"><input type="hidden" name="modified" value="<%= modData[0].ID %>">用户名: <input type="text" name="username" autofocus="autofocus" value="<%=modData[0].username%>"><br>邮箱: <input type="email" name="email" value="<%=modData[0].email%>"><br>头像: <input type="file" name="pic_header"><br><input type="submit" value="确认修改"></form>
</div>
<%}%>
<table><tr><th class="id">ID</th><th class="title">名字</th><th class="author">邮箱</th><th class="summary">头像</th><th class="operation">操作</th></tr><% for(var i = 0;i<usersData.length;i++){%><tr><td><%=usersData[i].ID%></td><td><%=usersData[i].username%></td><td><%=usersData[i].email%></td><td><img src="<%=usersData[i].pic_header%>" alt=""></td><td><a href="?action=del&id=<%=usersData[i].ID%>" onclick="return confirm('确定删除?')"><button>删除</button></a><a href="?action=mod&id=<%=usersData[i].ID%>"><button>修改</button></a></td></tr><%}%>
</table>
</body>
</html>