【Nodejs】基于express|ejs的用户博客管理系统前后端代码

目录

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>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/323252.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何查找iPhone中所有的应用程序

​ ​ Apple 的 App Store 共有约 200 万个适用于 iPhone 和 iPad 的应用程序。如果您像我们一样&#xff0c;您的 iOS 或 iPadOS 设备上可能有数十个应用程序&#xff0c;但没有机会将它们全部整理好。您很容易忘记主屏幕上应用程序图标的位置。 幸运的是&#xff0c;iPhone…

BLE Mesh蓝牙组网技术详细解析之Model Layer模型层(八)

目录 一、什么是BLE Mesh Model Layer模型层&#xff1f; 二、SIG Model 2.1 模型概念 2.2 消息格式 2.3 开关模型 四、资料获取 一、什么是BLE Mesh Model Layer模型层&#xff1f; Models Layer的作用是定义了一些通用的或特定的模型&#xff0c;用于实现网络节点设备…

【管理篇 / 恢复】❀ 07. macOS下用命令刷新固件 ❀ FortiGate 防火墙

【简介】随着苹果电脑的普及&#xff0c;很多管理员都会通过苹果电脑对飞塔防火墙进行管理。当防火墙需要命令状态下刷新固件时&#xff0c;在macOS下用命令刷新固件&#xff0c;将会是一个小小的挑战。 首先是硬件的连接&#xff0c;USB配置线的USB一头&#xff0c;接入MAC的U…

羊大师讲解每天坚持去散步,你的身体将会感受到奇迹的变化!

羊大师讲解每天坚持去散步&#xff0c;你的身体将会感受到奇迹的变化&#xff01; 每天都在忙碌的工作中度过&#xff0c;中午休息时间&#xff0c;你是否留给自己一点时间去散散步呢&#xff1f;或者晚上结束所有的工作后&#xff0c;是否会选择去散步&#xff0c;放松一下自…

学生社会实践周是什么意思

为何学校会安排社会实践周这样的活动&#xff1f;是为了让学生们走出课堂&#xff0c;接触真实的社会吗&#xff1f;还是为了让他们在实践中学习课本之外的知识和技能&#xff1f; 什么是社会实践周。简而言之&#xff0c;就是学校组织的一次为期一周的社会实践活动。在这一周…

前端结合MQTT实现连接 订阅发送信息等操作 VUE3

MQTT客户端下载 使用测试 在我之前文章中 MQTT下载基础使用 下面记录一下前端使用的话的操作 1.安装 npm i mqtt引入 import * as mqtt from "mqtt/dist/mqtt.min"; //VUE3 import mqtt from mqtt //VUE2 一、MQTT协议中的方法 Connect。等待与服务器建立连接…

使用代理IP实现爬虫的匿名性

目录 前言 一、什么是代理IP&#xff1f; 二、使用Python实现代理IP爬虫 1. 安装所需模块 2. 获取代理IP列表 3. 使用代理IP进行爬取 4. 使用代理IP进行数据抓取 三、总结 前言 随着互联网的快速发展&#xff0c;网络爬虫已经成为了获取互联网数据的一种重要方式。然而…

【uniapp】多规格选择

效果图 VUE <template> <view><view class"wp-80 pd-tb-40 mg-auto"><button type"warn" click"showDrawer(showRight)">筛选</button></view><!-- 筛选-uni-drawer --><uni-drawer ref"s…

CentOS 7 基于官方源码和openssl制作openssh 9.6 rpm包(含ssh-copy-id) —— 筑梦之路

之前写了一篇&#xff1a; CentOS 7 制作openssh 9.6 rpm包更新修复安全漏洞 —— 筑梦之路_升级openssh9.6-CSDN博客 有好几个网友反馈&#xff0c;ssh-keygen生成密钥存在问题&#xff0c;之前的rsa \ dsa加密算法用不了&#xff0c;因此写了一篇&#xff1a; 关于openssh…

基于ssm的班级事务管理系统+vue论文

摘 要 在如今社会上&#xff0c;关于信息上面的处理&#xff0c;没有任何一个企业或者个人会忽视&#xff0c;如何让信息急速传递&#xff0c;并且归档储存查询&#xff0c;采用之前的纸张记录模式已经不符合当前使用要求了。所以&#xff0c;对班级事务信息管理的提升&#x…

Java TBA访问NetSuite Restlet时的403错误

本周有同学问为啥Java访问NetSuite Restlet时&#xff0c;按照知识会之前的文章分享&#xff0c;会一直报403 INVALID_LOGIN_ATTEMPT错误。 https://nk-community.blog.csdn.net/article/details/131399801https://nk-community.blog.csdn.net/article/details/131399801原因是…

(03)光刻——半导体电路的绘制

01、绘制精细电路的第一步 金属-氧化物半导体场效应晶体管(MOSFET)的革命,让我们可以在相同面积的晶圆上同时制造出更多晶体管。MOSFET体积越小,单个 MOSFET的耗电量就越少,还可以制造出更多的晶体管,让其发挥作用,可谓是一举多得。可见,制造更小的MOSFET成了关键因素…