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

2024-01-05 15:20

本文主要是介绍【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>

这篇关于【Nodejs】基于express|ejs的用户博客管理系统前后端代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/573305

相关文章

Python将博客内容html导出为Markdown格式

《Python将博客内容html导出为Markdown格式》Python将博客内容html导出为Markdown格式,通过博客url地址抓取文章,分析并提取出文章标题和内容,将内容构建成html,再转... 目录一、为什么要搞?二、准备如何搞?三、说搞咱就搞!抓取文章提取内容构建html转存markdown

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

C#使用SQLite进行大数据量高效处理的代码示例

《C#使用SQLite进行大数据量高效处理的代码示例》在软件开发中,高效处理大数据量是一个常见且具有挑战性的任务,SQLite因其零配置、嵌入式、跨平台的特性,成为许多开发者的首选数据库,本文将深入探... 目录前言准备工作数据实体核心技术批量插入:从乌龟到猎豹的蜕变分页查询:加载百万数据异步处理:拒绝界面

用js控制视频播放进度基本示例代码

《用js控制视频播放进度基本示例代码》写前端的时候,很多的时候是需要支持要网页视频播放的功能,下面这篇文章主要给大家介绍了关于用js控制视频播放进度的相关资料,文中通过代码介绍的非常详细,需要的朋友可... 目录前言html部分:JavaScript部分:注意:总结前言在javascript中控制视频播放

Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能(代码示例)

《SpringBoot3.4.3基于SpringWebFlux实现SSE功能(代码示例)》SpringBoot3.4.3结合SpringWebFlux实现SSE功能,为实时数据推送提供... 目录1. SSE 简介1.1 什么是 SSE?1.2 SSE 的优点1.3 适用场景2. Spring WebFlu

java之Objects.nonNull用法代码解读

《java之Objects.nonNull用法代码解读》:本文主要介绍java之Objects.nonNull用法代码,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录Java之Objects.nonwww.chinasem.cnNull用法代码Objects.nonN

SpringBoot实现MD5加盐算法的示例代码

《SpringBoot实现MD5加盐算法的示例代码》加盐算法是一种用于增强密码安全性的技术,本文主要介绍了SpringBoot实现MD5加盐算法的示例代码,文中通过示例代码介绍的非常详细,对大家的学习... 目录一、什么是加盐算法二、如何实现加盐算法2.1 加盐算法代码实现2.2 注册页面中进行密码加盐2.

python+opencv处理颜色之将目标颜色转换实例代码

《python+opencv处理颜色之将目标颜色转换实例代码》OpenCV是一个的跨平台计算机视觉库,可以运行在Linux、Windows和MacOS操作系统上,:本文主要介绍python+ope... 目录下面是代码+ 效果 + 解释转HSV: 关于颜色总是要转HSV的掩膜再标注总结 目标:将红色的部分滤

在C#中调用Python代码的两种实现方式

《在C#中调用Python代码的两种实现方式》:本文主要介绍在C#中调用Python代码的两种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C#调用python代码的方式1. 使用 Python.NET2. 使用外部进程调用 Python 脚本总结C#调