【Nodejs】基于Promise异步处理的博客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
}

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

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

相关文章

为什么亚马逊卖家一定要有独立站?新手低成本快速搭建跨境电商独立站完整图文教程

目录 前言:为什么亚马逊卖家一定要有独立站? 为什么不选Shopify建站? 效果展示 一、购买域名 二、购买主机托管 三、搭建网站 前言:为什么亚马逊卖家一定要有独立站? 最近不少卖家朋友来问独立站建站方面的问题…

桥接模式和NAT模式的区别

一、桥接模式(bridged networking) 在桥接模式下,VMWare虚拟出来的操作系统就像是局域网中一台独立的主机,它能够访问网内任何一台机器。 在桥接模式下,你必须手工为虚拟系统配置IP地址、子网掩码,并且还要和宿主机器处于同一网段,这样虚拟系统才能和宿主机器进行通信。 配置…

安全防御之授权和访问控制技术

授权和访问控制技术是安全防御中的重要组成部分,主要用于管理和限制对系统资源(如数据、应用程序等)的访问。授权控制用户可访问和操作的系统资源,而访问控制技术则负责在授权的基础上,确保只有经过授权的用户才能访问…

前端插件库-VUE3 使用 vue-codemirror 插件

VUE3 插件 vue-codemirror 使用步骤和实例、基于 CodeMirror ,适用于 Vue 的 Web 代码编辑器。 第一步:安装 vue-codemirror & codemirror 包 , 以及语言包 npm install codemirror --save npm install vue-codemirror --savenpm insta…

VS2022 创建windows服务-Windows Service

vs2022 2023等版本出现,似乎被忘记的早期的Windows Service服务是如何创建的呢?本文介绍了如何用新版本VS进行C#创建、安装、启动、监控、卸载简单的Windows Service 的内容步骤和注意事项。windows服务可以在windows中自动运行。 一、创建一个Windows …

Android 多线程简单使用

在Android中,可以使用Java的Thread类或者使用AsyncTask类来实现多线程功能。 使用Thread类实现多线程: public class MyThread extends Thread {Overridepublic void run() {// 在这里执行多线程任务// 可以通过调用Thread的静态方法sleep()模拟耗时操…

若依 参数验证、数据校验使用

参数验证 spring boot中可以用@Validated来校验数据,如果数据异常则会统一抛出异常,方便异常中心统一处理。 1、基础使用 因为spring boot已经引入了基础包,所以直接使用就可以了。首先在controller上声明@Validated需要对数据进行校验。 public AjaxResult add(@Validate…

基于价值认同的需求侧电能共享分布式交易策略(matlab完全复现)

目录 1 主要内容 2 部分程序 3 程序结果 4 下载链接 1 主要内容 该程序完全复现《基于价值认同的需求侧电能共享分布式交易策略》,针对电能共享市场的交易机制进行研究,提出了基于价值认同的需求侧电能共享分布式交易策略,旨在降低电力市…

基于SpringBoot的旅游网站281

文章目录 项目介绍主要功能截图:部分代码展示设计总结项目获取方式🍅 作者主页:超级无敌暴龙战士塔塔开 🍅 简介:Java领域优质创作者🏆、 简历模板、学习资料、面试题库【关注我,都给你】 🍅文末获取源码联系🍅 项目介绍 基于SpringBoot的旅游网站281,java项目。…

电锯切割狂

欢迎来到程序小院 电锯切割狂 玩法:把木块切成等分的碎片,每关都会有切割次数,木块数,切割越均匀分数越搞, 有简单、正常、困难、专家版,快去解锁不同版本进行切割吧^^。开始游戏https://www.ormcc.com/pl…

你vue有写过自定义指令吗?知道自定义指令的应用场景有哪些吗?

一、什么是指令 开始之前我们先学习一下指令系统这个词 指令系统是计算机硬件的语言系统,也叫机器语言,它是系统程序员看到的计算机的主要属性。因此指令系统表征了计算机的基本功能决定了机器所要求的能力 在vue中提供了一套为数据驱动视图更为方便的…

MySQL的基础架构之内部执行过程

MySQL的逻辑架构图 如上图所示,MySQL可以分为Server层和存储引擎层两部分: 1)Server层涵盖了MySQL的大多数核心服务功能,以及所有的内置函数(如日期、时间、数学和加密函数等),所有跨存储引擎…

linux新M2固态挂载

一、普通挂载 查看硬盘信息 sudo fdisk -l创建文件系统 sudo mkfs.ext4 /dev/nvme0n1创建挂载点 sudo mkdir /home/zain挂载 sudo mount /dev/nvme0n1 /home/zain二、永久挂载 vi /etc/fstabinsert: /dev/nvme0n1 /home/zain ext4 defaults 0 2 wqs…

知识笔记(六十九)———缓冲区溢出攻击

1. 什么是缓冲区溢出 (1)缓冲区 缓冲区是一块连续的计算机内存区域,用于在将数据从一个位置移到另一位置时临时存储数据。这些缓冲区通常位于 RAM 内存中,可保存相同数据类型的多个实例,如字符数组。 计算机经常使用…

3.10 Android eBPF HelloWorld调试(四)

一,读取eBPF map的android应用程序示例 1.1 C++源码及源码解读 /system/memory/bpfmapparsed/hello_world_map_parser.cpp //基于aosp android12#define LOG_TAG "BPF_MAP_PARSER"#include <log/log.h> #include <stdlib.h> #include <unistd.h&g…

Day22 112路径总和 113路径总和II 106中后构造二叉树/中前构造二叉树 654最大二叉树

给定一个二叉树和一个目标和&#xff0c;判断该树中是否存在根节点到叶子节点的路径&#xff0c;这条路径上所有节点值相加等于目标和。 递归&#xff1a; 可以采用深度优先的递归方式&#xff0c;前中后序都可以&#xff08;因为中节点没有处理逻辑&#xff09;。首先确定参…

放大镜Scratch-第14届蓝桥杯Scratch省赛真题第3题

3. 放大镜&#xff08;50分&#xff09; 评判标准&#xff1a; 10分&#xff1a;满足"具体要求"中的1&#xff09;&#xff1b; 15分&#xff1a;满足"具体要求"中的2&#xff09;&#xff1b; 25分&#xff0c;满足"具体要求"中的3&#xff…

C#高级:Lambda表达式分组处理2(WITH ROLLUP关键字)

目录 一、问题引入 二、with rollup查询 三、去掉多余数据 四、拓展 一、问题引入 查询SQL后结果如下&#xff0c;字段分别是用户、项目、批次、工作时间&#xff1a; SELECT UserID,ProjectID,ProBatchesID,WorkHour FROM MAINTABLE GROUP BY HourFiller ,ProjectID ,…

【ESP32接入国产大模型之文心一言】

1. 怎样接入文心一言 随着人工智能技术的不断发展&#xff0c;自然语言处理领域也得到了广泛的关注和应用。在这个领域中&#xff0c;文心一言作为一款强大的自然语言处理工具&#xff0c;具有许多重要的应用价值。本文将重点介绍如何通过ESP32接入国产大模型之文心一言api&am…

图片中src属性绑定不同的路径

vue3 需求是按钮disable的时候&#xff0c;显示灰色的icon&#xff1b;非disable状态&#xff0c;显示白色的icon 一开始src写成三元表达式&#xff0c;发现不行&#xff0c;网上说src不能写成三元表达式&#xff0c;vue会识别成字符串 最后的解决方案 同时&#xff0c;发现…