不使用框架完成博客项目(原生nodejs)

一、安装Koa

  • npm install koa-generator -g
  • koa2 blog-koa2
  • cd blog-koa2
  • npm install
  • npm i cross-env --save-dev
  • 启动项目npm run dev
  • 代码复用

二、登录验证

  • 下载插件 koa-generic-session、koa-redis、redis
    npm i koa-generic-session koa-redis redis --save
  • 配置环境(app.js)
const session = require('koa-generic-session')
const redisStore = require('koa-redis')
const REDIS_CONF = require('./conf/db')
//session 与  redis
app.keys = ['dfhQWE_123#df']
app.use(session({//配置cookiecookie:{path:"/",httpOnly:true,maxAge:24 * 60 * 60 * 1000},//配置redisstore: redisStore({all:`${REDIS_CONF.host}:${REDIS_CONF.port}`})
}))
  • 中间键
const {ErrorModel} = require('../model/resModel')module.exports = async (ctx, next) => {if (ctx.session.username) {await next()return }ctx.body = new ErrorModel('尚未登陆')
}

三、修改controller层代码

  • 获取博客列表
const getList = async (author, keyword) => {let sql = `select * from blogs where 1=1 `if (author) {author = escape(author)sql += ` and author = ${author} `}if (keyword) {keyword = escape(keyword)sql += ` and title like %${keyword}%`}sql += 'order by createtime desc; 'return await exec(sql)
}
  • 获取博客详细内容
const getDetail = async (id) => {id = escape(id)let sql = `select content,title,author,id from blogs where id = ${id}`const rows = await exec(sql)return rows[0]
}
  • 更新博客
const updateBlog = async (id, blogData = {}) => {const content = escape(xss(blogData.content))const title = escape(xss(blogData.title))id = escape(xss(id))let sql = `update blogs set title=${title}, content=${content} where id=${id}`const updateData = await exec(sql)if (updateData.affectedRows > 0) {return true}return false
}
  • 删除博客
const delBlog = async (id, author) => {id = escape(xss(id))author = escape(xss(author))let sql = `delete from blogs where id=${id} and author=${author};`const delData = exec(sql)if (delData.affectedRows > 0) {return true}return false
}
  • 增加博客
const newBlog = async (blogData = {}) => {const title = escape(xss(blogData.title))const content = escape(xss(blogData.content))const author = escape(xss(blogData.author))const createTime = Date.now()const sql = `insert into blogs (title, content, createtime, author)values (${title}, ${content}, ${createTime}, ${author})`const insertData = await exec(sql)return {id: insertData.insertId}
}
  • 用户登录
const {exec,escape} = require('../db/mysql')
const xss = require('xss')
const login = async(username,paasword) => {username = escape(xss(username))paasword = escape(xss(paasword))let sql = `select username, realname from users where username=${username} and password=${password}`const row = await exec(sql)return row[0] || {}
}

四、router层

  • 查看博客列表
router.get('/list', async (ctx, next) => {let author = ctx.query.author || ''const keyword = ctx.query.keyword || ''if (ctx.query.isadmin) {if (ctx.session.username == null) {ctx.body = new ErrorModel('尚未登录')}author = ctx.session.username}const listData = await getList(author, keyword)ctx.body = new SuccessModel(listData)
})
  • 查看博客详细信息
router.get('/detail', async (ctx, next) => {const { id } = ctx.queryconst detail = await getDetail(id)ctx.body = new SuccessModel(detail)
})
  • 增加博客
const loginCheck = require('../middleware/loginCheck')
router.post('/new', loginCheck, async (ctx, next) => {ctx.request.body.author = ctx.session.usernameconst id = await newBlog(ctx.request.body)if (id > 0) {ctx.body = new SuccessModel()return} else {ctx.body = new ErrorModel('增加博客失败')}
})
  • 删除博客
const loginCheck = require('../middleware/loginCheck')
router.post('/del', loginCheck, async (ctx, next) => {const { id } = ctx.queryconst author = ctx.session.usernameconst val = await delBlog(id, author)if (val) {ctx.body = new SuccessModel()return} else {ctx.body = new ErrorModel('删除博客失败')} })
  • 更新博客
const loginCheck = require('../middleware/loginCheck')
router.post('/update', loginCheck, async (ctx, next) => {const { id } = ctx.queryctx.request.body.author = ctx.session.usernameconst val = await updateBlog(id, ctx.request.body)if (val) {ctx.body = new SuccessModel()return} else {ctx.body = new ErrorModel('更新博客失败')}
})
  • 用户登录
router.post('/login', async(ctx, next) => {//获取请求数据const {username, password} = ctx.request.bodyconst data = await login(username,password)if (data.username) {ctx.session.username = data.usernamectx.session.realname = data.realnamectx.body= new SuccessModel()return}ctx.body = new ErrorModel('登录失败')
})

五、接口测试

  • 查看博客列表

  • 查看博客详细内容


  • 用户登录

  • 增加博客

  • 更新博客

  • 删除博客

  • 未登录进行博客操作


六、使用morgan写日志

  • 安装 koa-morgan
    npm i koa-morgan --save
const fs = require('fs')
const path = require('path')
const morgan = require('koa-morgan')
const ENV = process.env.NODE_ENV
if (ENV !== 'production') {app.use(morgan('dev'),{stream:process.stdout //打印到控制台 (默认)})
} else {//线上环境const logfileName = path.join(__dirname, "logs","access.log")const writeStream = fs.createWriteStream(logfileName, {flags:'a'})app.use(morgan('combined',{stream:writeStream}))
}

使用express重构博客项目

源码下载

欢迎访问我的个人博客

使用Koa2重构博客项目相关推荐

  1. 分享Node.js + Koa2 + MySQL + Vue.js 实战开发一套完整个人博客项目网站

    这是个什么的项目? 使用 Node.js + Koa2 + MySQL + Vue.js 实战开发一套完整个人博客项目网站. 博客线上地址:www.boblog.com Github地址:https: ...

  2. Python Web开发:Django+BootStrap实现简单的博客项目

    创建blog的项目结构 关于如何创建一个Django项目,请查看[Python Web开发:使用Django框架创建HolleWorld项目] 创建blog的数据模型 创建一个文章类 所有开发都是数据 ...

  3. docker部署博客项目

    docker 部署博客项目 发现很久没有写文章了,等我的博客完成,我应该也会继续写的 连接远程服务器 ssh root@xxxxxx yum更新一下 yum update 用来解压zip压缩包 yum ...

  4. SpringCloud开发个人博客项目(框架搭建)

    1. SpringCloud简介 我们先看看springCloud官网(https://spring.io/projects/spring-cloud#overview)上的介绍: Spring Cl ...

  5. 麦司机博客项目技术选型-Java后端

    麦司机博客项目 博客主页:maisiji.cn/ github地址:github.com/fendoudebb/- Java后端技术选型介绍 SpringBoot: 后端框架 项目主页: spring ...

  6. Django之BBS博客项目

    一.登陆功能(验证码) 1 from geetest importGeetestLib2 from django.contrib importauth3 4 #使用极验滑动验证码的登陆 5 deflo ...

  7. 00-基于Vue的博客项目展示

    目录 0 项目开源地址 1 博客页面展示 1.1 首页 1.2 文章页 2 后台管理页面展示 2.1 登录页面 2.2 新建文章-Markdown编辑器 2.3 新建文章-富文本编辑器 2.4 文章列 ...

  8. 码神之路博客项目构建记录

    个人博客项目 Blog 一.项目搭建(2021.10.6) pom文件导入相关依赖 application配置文件配置 Mybatis Plus配置 跨域问题解决 二.首页配置 首页分页显示文章信息 ...

  9. 基于 abp vNext 和 .NET Core 开发博客项目 - 终结篇之发布项目

    基于 abp vNext 和 .NET Core 开发博客项目 - 终结篇之发布项目 转载于:https://github.com/Meowv/Blog 既然开发完成了,还是拿出来溜溜比较好,本篇是本 ...

  10. 基于 abp vNext 和 .NET Core 开发博客项目 - Blazor 实战系列(九)

    基于 abp vNext 和 .NET Core 开发博客项目 - Blazor 实战系列(九) 转载于:https://github.com/Meowv/Blog 终于要接近尾声了,上一篇基本上将文 ...

最新文章

  1. Stanford NLP 解读 ACL 2018 论文——用于调试 NLP 模型的语义等价对立规则
  2. pwn(ctf)中常见的系统调用
  3. 2019牛客暑期多校训练营(第七场)D Number(思维)
  4. FreeSql.Generator命令行代码生成器是如何实现的
  5. Linux如何进行GPIO读写操作的?
  6. 如何制定项目里程碑?
  7. SPECT/PECT成像原理
  8. PHP - 使用file_get_contents下载远程文件到本地
  9. 学习可爱彩色线条PS极简马克笔简笔画:饮品篇
  10. 卸载手机模拟大师MobileEmuMaster!!!
  11. 东原服务器开机显示bb,启用tls后,服务器出现remote error: tls: bad certificate
  12. 《Steam平台上的VR虚拟现实》(Yanlz+Unity+XR+VR+AR+MR+Steam+SteamVR+Vive+Oculus+Valve+立钻哥哥+==)
  13. 【Python】丘比特之箭,一箭穿心,快去发给你心仪的人叭~
  14. 多元线性回归分析spss结果解读_SPSS--回归-多元线性回归模型案例解析
  15. 别太在意人走茶凉 物是人非
  16. CODESYS自动化仿真软件如何与EtherNet IP工业RID读写器|读卡器CK-RF102AN-E01联机工作
  17. 计算机c语言二级题库及答案txt,计算机二级c语言题库及答案
  18. 现代社会,各行各业的竞争越来越激烈
  19. python怎么画地图空间分异图_基于地形梯度的赣南地区生态系统服务价值对人为干扰的空间响应...
  20. XYOJ1257: 捕杀恶龙(break+j=k)

热门文章

  1. ffmpeg文档7:快进快退
  2. sort()函数关于结构内容要怎么写
  3. 使用curl与wget发送get与post请求
  4. python lambda函数 与 函数式编程
  5. c++ 读文件_C语言文件操作大全
  6. linux sed批量更改文件,Linux利用sed批量修改文件名(示例代码)
  7. 4月10日服务器例行维护公告,4月12日服务器例行维护公告(已完成)
  8. PHP上传的文件权限不足,上传文件的PHP脚本不工作的问题(目录权限问题)php-fpm+nginx...
  9. MySQL抽稀_Android GPS定位轨迹抽稀之道格拉斯-普克(Douglas-Peuker)算法详解
  10. html5 crop,HTML5内联SVG autocrop空格