【Nodejs】基于Promise异步处理的博客demo代码实现

news2025/5/25 21:33:07

目录

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');

    //获取path
    const url=req.url;
    req.path=url.split('?')[0];

    //解析query
    req.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.coloradmin.cn/o/1355732.html

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

相关文章

VR云游开启智慧旅游新纪元,打造“云旅游”新模式

元旦假期,全国文化和旅游市场平稳有序,家人和亲友的出游趋势稳步增加,演唱会、音乐节、跨年等活动的叠加让元旦出游更加吸引游客。在冰雪旅游热度持续攀升的时候,许多年轻群体已经开始使用VR云游进行智慧景区旅游,身临…

作业--day41

利用模板类完成顺序表 #include <iostream>using namespace std;//模板类 template <typename T> class SeqTab{T arr[20];int maxsize; public:SeqTab():maxsize(0){}void Insert(T a);void Search(T a);void Delete(int index);void Show(); };//尾插 template …

bullet3 三种碰撞检测及实现

Bullet 物理引擎是一个专业的开放源码的碰撞检测&#xff0c;刚体和柔体动力学库。Bullet 物理引擎目标是实时和交互使用在游戏&#xff0c;电影和机器人的视觉效果。自由zlib授权的商业使用库。 bullet3的三种碰撞检测 以下三种方式都是可以达到碰撞检测的效果&#xff1a; …

新能源汽车@2023/24:卷价格、拼智能与生态战

【潮汐商业评论/原创】 2023年末尾&#xff0c;受到大众广泛热议的小米汽车发布会“姗姗来迟”&#xff0c;也为“乱战”中的2023新能源汽车市场画上了一个句号。 然而&#xff0c;在雷军整整三个小时看似平和的演讲与技术讲解中&#xff0c;实则在电机、智驾、智舱等核心技术…

多元线性回归案例--客户价值模型

文章目录 step 1&#xff1a;读取数据step 2&#xff1a;搭建模型step 3&#xff1a;构造回归方程step 4&#xff1a;评估模型 利用多元线性回归模型可以根据多个因素来预测客户价值&#xff0c;当模型搭建完成后&#xff0c;便可对不同价值的客户采用不同的业务策略。 这里以信…

C#高级语法 Attribute特性详解和类型,方法,变量附加特性讲解

文章目录 前言相关资料Attribute特性个人原理理解特性的声明与使用类型特性运行结果&#xff1a; 找到类的Attribute属性方法特性和变量特性代码封装测试类TestService1TestService2TestService3 测试代码运行结果 对封装的代码进行优化封装代码测试代码运行结果&#xff08;和…

雾天条件下 SLS 融合网络的三维目标检测

论文地址&#xff1a;3D Object Detection with SLS-Fusion Network in Foggy Weather Conditions 论文代码&#xff1a;https://github.com/maiminh1996/SLS-Fusion 论文摘要 摄像头或激光雷达&#xff08;光检测和测距&#xff09;等传感器的作用对于自动驾驶汽车的环境意识…

3D 纹理的综合指南

在线工具推荐&#xff1a;3D数字孪生场景编辑器 - GLTF/GLB材质纹理编辑器 - 3D模型在线转换 - Three.js AI自动纹理开发包 - YOLO 虚幻合成数据生成器 - 三维模型预览图生成器 - 3D模型语义搜索引擎 我们经常看到超现实主义的视频游戏和动画电影角色出现在屏幕上。他们皮肤上的…

在win10上cuda12+tensorrt8.6+vs2019环境下编译paddle2.6生成python包与c++推理库

paddle infer官方目前没有发布基于cuda12的c库&#xff0c;为此参考https://www.paddlepaddle.org.cn/inference/user_guides/source_compile.html实现cuda12的编译安装&#xff0c;不料博主才边缘好自己的paddle2.6&#xff0c;paddle官方已经发布了cuda12.0的paddle2.6框架。…

嵌入式MCU:如何安装codeWarrior 和Jlink

先安装codeWarrior 15.0版本,这个官网上没有这个版本要去blazar的这个网站上下载: Blazar-α系统电路图纸(MOOC课程对应)(Updating)-Blazar开源硬件与MOOC codeWarrior 安装不要安装在中文路径里面 安装完了codeWarrior 再安装Jlink 然后再装Jlink 这个也是从上面的…

Android 内容生成pdf文件

1.引入itext7 implementation com.itextpdf:itext7-core:7.1.13上面比较大&#xff0c;可以直接下载需要集成的jar包 implementation files(libs\\layout-7.1.13.jar) implementation files(libs\\kernel-7.1.13.jar) implementation files(libs\\io-7.1.13.jar) implementatio…

《MySQL系列-InnoDB引擎04》MySQL表相关介绍

文章目录 第四章 表1 索引组织表2 InnoDB逻辑存储结构2.1 表空间2.2 段2.3 区2.4 页2.5 行2.6 拓展&#xff1a;MySQL的varchar(n)能存储几个字符&#xff1f;占多少字节&#xff1f; 3 InnoDB行记录格式4 文件格式5 约束5.1 数据完整性5.2 约束的创建和查找5.3 约束和索引的区…

如何为项目创建高效的项目进度表?

项目管理是一项负有巨大责任的工作&#xff0c;涉及到完成项目所需的大量流程和任务。如果没有任务和责任的线路图&#xff0c;很容易就偏离方向&#xff0c;无法了解项目每个阶段需要完成的任务。这就是为什么项目进度表是成功执行项目的核心所在。 什么是项目进度表&#xff…

数据分析-24-母婴产品电商可视化分析(包含代码数据)

文章目录 0. 代码数据获取1. 项目1.1 项目介绍1.2 分析目的1.3 分析思路 2. 数据集介绍2.1 数据信息2.2 字段含义 3. 数据清洗3.1 导入包和查看数据3.2 查看列的信息3.3 查看表平均值这些3.4 查出重复的user_id3.5 清洗buy_mount列 4. 针对目的进行分析4.1 销量数量前10的类别I…

T40N 君正智能处理器T40 BGA 芯片

T40N是一款智能视频应用处理器&#xff0c;适用于移动摄像机、安防等视频设备调查、视频聊天、视频分析等。该SoC引入了一种创新的体系结构满足高性能计算和高质量图像和视频编码的要求通过视频设备解决。T40N提供高速CPU计算能力&#xff0c;出色的图像信号过程中&#xff0c;…

ensp vlan连接(详细)

1.将需要的设备放置好 2.将设备连接起来 3.启动所有设备 4.备注好每台PC机的信息 5.配置好每台PC机 6.配置交换机1 进入配置视图&#xff0c;关闭信息提示 重命名设备 批量创建VLAN 开始配置接口 更改接口类型为ACCESS 将接口划分到对应的VLANN 配置下一个接口&#xff0c;步…

JavaScript高级程序设计读书记录(一):语言基础,语法,变量,数据类型

1. 语法 很大程度上借鉴了 C 语言和其他类 C 语言&#xff0c;如 Java 和 Perl. 1.1 区分大小写 1.2 标识符 第一个字符必须是一个字母、下划线&#xff08;_&#xff09;或美元符号&#xff08;$&#xff09;&#xff1b; 剩下的其他字符可以是字母、下划线、美元符号或数…

qiankun 公共依赖

1、提取公共依赖的目的 减少相同资源的重复加载资源版本不同步打包文件庞大2、如何提取公共依赖 基本思路&#xff1a;1、相同依赖 采用 CDN 的方式加载&#xff0c;并把 所有依赖的 CDN 链接 统一放到一个文件中进行管理 2、把存放 CDN 链接的文件&#xff0c;引入到 vue.conf…

NFT 项目入驻 NFTScan Site 流程说明

NFTScan Site 是由数据基础设施 NFTScan 推出的功能强大的 NFT 项目管理平台。NFTScan Site 主要为 NFT Collection、NFT Marketplace、NFTFi 以及其他 NFT 生态项目提供专业的项目管理后台服务和链上数据分析追踪服务。 NFTScan Site 功能&#xff1a; 1&#xff09;项目信息编…

华硕ASUS RT-AC1200 pandavan老毛子 128M DDR固件

原版硬件只支持64M DDR2&#xff0c;更换了128M内存&#xff0c;结果找不到对应的固件&#xff0c;而且全部都是英文版的 所以自己编译了中文版的pandavan老毛子&#xff0c;下载位置可能资源审核中&#xff1a;