当前位置: 首页 > news >正文

【Nodejs】基于node http模块的博客demo代码实现

目录

package.json

www.js

db.js

app.js

routes/blog.js

controllers/blog.js

mysql.js

responseModel.js


无开发,不安全。

这个demo项目实现了用Promise异步处理http的GET和POST请求,通过mysql的api实现了博客增删改查功能,但因没有写登录身份认证功能,所以限制具体博客增删时的权限就用了假数据。

下面直接贴出源码:

package.json

{"name": "nodetest","version": "1.0.0","description": "","main": "bin/www.js","scripts": {"dev": "nodemon bin/www.js"},"keywords": [],"author": "","license": "ISC","devDependencies": {"nodemon": "^3.0.2"},"dependencies": {"mysql": "^2.18.1"}
}

这里用的是nodemon监视文件系统的更改,并自动重启 Node.js 应用程序

运行:npm run dev

www.js

//创建服务器
const http=require('http');
const serverHandler=require('../app');
const PORT =5000;
const server=http.createServer(serverHandler);server.listen(PORT,()=>
{console.log('server running at port 5000...');
})

db.js

let MYSQL_CONFIG={};MYSQL_CONFIG={host:'localhost',user:'root',password:'root',port:3306,database:'nodeblog'
}module.exports={MYSQL_CONFIG
}

app.js

//业务逻辑代码
const querystring = require('querystring');
const handleBlogRoute=require('./src/routes/blog');//处理POST数据
const getPostData=(req)=>{const promise=new Promise((resolve,reject)=>{if(req.method!=='POST'){resolve({});return;}if(req.headers['content-type']!=='application/json'){resolve({});return;}let postData='';req.on('data',(chunk)=>{postData+=chunk.toString();});req.on('end',()=>{if(!postData){resolve({});return;}resolve(JSON.parse(postData));});});return promise;
}
const serverHandler=(req,res)=>
{//设置相应格式res.setHeader('Content-Type','application/json');//获取pathconst url=req.url;req.path=url.split('?')[0];//解析queryreq.query=querystring.parse(url.split('?')[1]);//处理POST数据getPostData(req).then((postData)=>{req.body=postData;//博客相关的路由const blogDataPromise=handleBlogRoute(req,res);if (blogDataPromise){blogDataPromise.then((blogData)=>{res.end(JSON.stringify(blogData));});return;}//未匹配到任何路由res.writeHead(404,{'Content-Type':'text/plain'});res.write('404 Not Found');res.end();});}module.exports=serverHandler;

routes/blog.js

//处理博客相关的路由
const {SuccessModel, ErrorModel}=require('../model/responseModel');
const {getList,getDetail,createNewBlog,updateBlog,deleteBlog} = require('../controllers/blog');const handleBlogRoute=(req,res)=>
{const method=req.method;const blogData=req.body;const id=req.query.id;if(method==='GET' && req.path==='/api/blog/list'){const author=req.query.author||'';const keyword=req.query.keyword||'';const listDataPromise=getList(author,keyword);return listDataPromise.then((listData)=>{return new SuccessModel(listData);});}if(method==='GET' && req.path==='/api/blog/detail'){const detailDataPromise=getDetail(id);return detailDataPromise.then(detailData=>{return new SuccessModel(detailData);})}if(method==='POST' && req.path==='/api/blog/new'){const author='Hacker';req.body.author=author;const newBlogDataPromise=createNewBlog(blogData);return newBlogDataPromise.then(newBlogData=>{return new SuccessModel(newBlogData);});}if(method==='POST' && req.path==='/api/blog/update'){const updatedBlogDataPromise=updateBlog(id,blogData);return updatedBlogDataPromise.then((updatedBlogData)=>{if (updatedBlogData){return new SuccessModel('更新博客成功!');}else{return new ErrorModel('更新博客失败...');}});}if(method==='POST' && req.path==='/api/blog/delete'){const author='Hacker';const deleteBlogDataPromise=deleteBlog(id,author);return deleteBlogDataPromise.then((deleteBlogData)=>{if (deleteBlogData){return  new SuccessModel('删除博客成功!');}else{return new ErrorModel('删除博客失败...');}});}}module.exports=handleBlogRoute;

controllers/blog.js

const {execSQL}=require('../db/mysql');//获取博客列表
const getList=(author,keyword)=>{let sql=`select * from blogs where`;if(author){sql+=` author='${author}' `;}if(keyword){sql+=`and title like '%${keyword}%'`;}return execSQL(sql);
}//获取博客详情
const getDetail=(id)=>{const sql=`select * from blogs where id='${id}'`;return execSQL(sql).then(rows=>{console.log('rows',rows);return rows[0];});
}//创建新的博客
const createNewBlog=(blogData={})=>{const title=blogData.title;const content=blogData.content;const author=blogData.author;const createdAt=Date.now();const sql=`insert into blogs (title,content,author,createdAt) values ('${title}','${content}','${author}',${createdAt})`;return execSQL(sql).then(insertedResult=>{console.log('insertedResult',insertedResult);return {id:insertedResult.insertId}});}const updateBlog=(id,blogData={})=>{const title=blogData.title;const content=blogData.title;const sql=`update blogs set title='${title}', content='${content}' where id=${id}`;return execSQL(sql).then(updateResult=>{console.log('updateResult',updateResult);if(updateResult.affectedRows>0){return true;}return false;})
}const deleteBlog=(id,author)=>{const sql=`delete from blogs where id=${id} and author='${author}'`;return execSQL(sql).then(deleteResult=>{console.log('deleteResult',deleteResult);if(deleteResult.affectedRows>0){return true;}return false;})
}
module.exports={getList,getDetail,createNewBlog,updateBlog,deleteBlog
}

mysql.js

const mysql=require('mysql');
const { MYSQL_CONFIG } = require('../config/db');const connection=mysql.createConnection( MYSQL_CONFIG);//开始连接
connection.connect();//执行sql语句
function execSQL(sql){const promise=new Promise((resolve,reject)=>{connection.query(sql,(err,result)=>{if(err){reject(err);return;}resolve(result);})
})return promise;
}module.exports={execSQL
}

responseModel.js

class BaseModel{constructor(data,message){if(typeof data==='string'){this.message=data;data=null;message=null;}if(data){this.data=data;}if(message){this.message=message;}}
}class SuccessModel extends BaseModel{constructor(data,message){super(data,message);this.errno=0;}
}class ErrorModel extends BaseModel{constructor(data,message){super(data,message);this.errno=-1;}
}module.exports = {SuccessModel,ErrorModel
}

相关文章:

  • Go后端开发 -- Go Modules
  • x-cmd pkg | trafilatura - 网络爬虫和搜索引擎优化工具
  • async和await关键字
  • 解析千兆多模光模块SFP-GE-SX
  • 可视化速通知识点
  • kotlin isEmpty/isNotEmpty/isNullOrEmpty和isBlank/isNotBlank/isNullOrBlank
  • 数据结构期末复习(1)数据结构和算法 线性表
  • 个人实际开发心得感悟及学习方法
  • Vue中的组件通信方式及应用场景
  • 2024年道路运输企业主要负责人证考试题库及道路运输企业主要负责人试题解析
  • 各种基础环境搭建
  • Danil Pristupov Fork(强大而易用的Git客户端) for Mac/Windows
  • Keil5,ARM编译器 软件优化注意事项
  • 如何利用firewalld抵御DDOS攻击
  • pyqt6 + pycharm 搭建+使用入门
  • [PHP内核探索]PHP中的哈希表
  • 【347天】每日项目总结系列085(2018.01.18)
  • 【跃迁之路】【585天】程序员高效学习方法论探索系列(实验阶段342-2018.09.13)...
  • AzureCon上微软宣布了哪些容器相关的重磅消息
  • Mac 鼠须管 Rime 输入法 安装五笔输入法 教程
  • Node项目之评分系统(二)- 数据库设计
  • npx命令介绍
  • PHP的Ev教程三(Periodic watcher)
  • Spring框架之我见(三)——IOC、AOP
  • -- 查询加强-- 使用如何where子句进行筛选,% _ like的使用
  • 翻译:Hystrix - How To Use
  • 给新手的新浪微博 SDK 集成教程【一】
  • 基于遗传算法的优化问题求解
  • 理解在java “”i=i++;”所发生的事情
  • 浅谈web中前端模板引擎的使用
  • 容器服务kubernetes弹性伸缩高级用法
  • 使用Swoole加速Laravel(正式环境中)
  • 算法-图和图算法
  • 微信支付JSAPI,实测!终极方案
  • 因为阿里,他们成了“杭漂”
  • zabbix3.2监控linux磁盘IO
  • 长三角G60科创走廊智能驾驶产业联盟揭牌成立,近80家企业助力智能驾驶行业发展 ...
  • ​创新驱动,边缘计算领袖:亚马逊云科技海外服务器服务再进化
  • (2)STM32单片机上位机
  • (C++)八皇后问题
  • (c语言版)滑动窗口 给定一个字符串,只包含字母和数字,按要求找出字符串中的最长(连续)子串的长度
  • (附源码)springboot人体健康检测微信小程序 毕业设计 012142
  • (每日持续更新)jdk api之StringBufferInputStream基础、应用、实战
  • (四)Tiki-taka算法(TTA)求解无人机三维路径规划研究(MATLAB)
  • (原創) 如何安裝Linux版本的Quartus II? (SOC) (Quartus II) (Linux) (RedHat) (VirtualBox)
  • (中等) HDU 4370 0 or 1,建模+Dijkstra。
  • (转)http-server应用
  • .net Application的目录
  • .net 写了一个支持重试、熔断和超时策略的 HttpClient 实例池
  • .net 逐行读取大文本文件_如何使用 Java 灵活读取 Excel 内容 ?
  • .net遍历html中全部的中文,ASP.NET中遍历页面的所有button控件
  • .NET使用存储过程实现对数据库的增删改查
  • [ Linux 长征路第五篇 ] make/Makefile Linux项目自动化创建工具
  • [20171102]视图v$session中process字段含义
  • [AIGC] MySQL存储引擎详解