NodeJS - Blog (无框架)

VSCODE

1. VSCODE  crl+K+C/U 注释与反注释;ctrl +[ / ] 缩进

2. launch.json 设置启用项目

blog-1 (Src\controller . model . router 逻辑分离)

 

 bin\www.js

const http=require('http')
const PORT=3000

const serverHandle=require('../app.js')
const server=http.createServer(serverHandle)

server.listen(PORT)

console.log('ok')

src\controller\blog.js

const getList =(author, keyword)=>{
    return [
        {
            id:1,
            title:"博客A",
            content:"内容A",
            createTime:"2022-03-01",
            author:"zhangshan"
        },
        {
            id:2,
            title:"博客B",
            content:"内容B",
            createTime:"2022-03-11",
            author:"lisi"
        }        
    ]


}

const getDetail =(id)=>{
    return {
        id:1,
        title:"博客A",
        content:"内容A",
        createTime:"2022-03-01",
        author:"zhangshan"
    }


}

const newBlog = (blogData={}) =>{
    // blogData  是一个博客对象
    console.log('new blog data ',blogData)
    return {
        id: 3
    }
}

const updateBlog =(id, blogData = {} ) =>{
    // blogData  是一个博客对象
    // id 是更新的Id
    console.log('update blog data ', id, blogData)
    return true
}

const delBlog =(id) =>{
    // blogData  是一个博客对象
    // id 是更新的Id
    console.log('delete blog data ', id)
    return true
}


module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    delBlog

}
 

 src\controller\blog.js

const loginCheck = (username,password) =>{
    if (username=== 'zhangshan' && password === '123' ) {
        return true
    }
    return false

}

module.exports = loginCheck
 
src\model\resModel.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.errorno=0
        }
 }

 class ErrorModel extends BaseModel{
    constructor(data,message) {
            super(data,message)
            this.errorno=-1
        }
 }
 
 module.exports={
    SuccessModel,
    ErrorModel
 }
 
src\router\blog.js
 
const {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    delBlog
} = require('../controller/blog')
const {SuccessModel,ErrorModel} = require('../model/resModel')

const handleBlogRouter = (req,res)=>{
    const method = req.method
    const id = req.query.id


    // 获取博客列表
    if (method === 'GET' && req.path === '/api/blog/list'){
        const keyword = req.query.keyword || ''
        const author = req.query.author || ''
        const data = getList(author,keyword)

        // return {
        //     msg: 'this is list for blog'
        // }
        return new SuccessModel(data)
    }


    // 获取博客详情
    if (method === 'GET' && req.path === '/api/blog/detail'){
        // return {
        //     msg: 'this is detail info for one blog'
        // }
        const data = getDetail(id)
        return new SuccessModel(data)
    }


    // 新建博客
    if (method === 'POST' && req.path === '/api/blog/new'){
        const data=newBlog(req.body)
        return new SuccessModel(data)
    }

    // 更新博客
    if (method === 'POST' && req.path === '/api/blog/update'){
        // return {
        //     msg: 'update blog'
        // }
        const result = updateBlog(id,req.body)
        if (result) {
            return new SuccessModel('更新成功!')
        }
        else{
            return new ErrorModel('更新博客失败!')
        }
    }

    // 删除博客
    if (method === 'POST' && req.path === '/api/blog/del'){
            // return {
            //     msg: 'Delete a blog'
            // }
            const result=delBlog(id)
            if (result) {
                return new SuccessModel('删除成功!')
            }
            else{
                return new ErrorModel('删除博客失败!')
            }
    }
}


module.exports = handleBlogRouter
 
src\router\user.js
const loginCheck = require('../controller/user')
const {SuccessModel,ErrorModel} = require('../model/resModel')

const handleUserRouter = (req,res)=>{
    const method = req.method


    // 用户登录
    if (method === 'POST' && req.path === '/api/user/login'){
         const {username,password} = req.body
         if (loginCheck(username,password)) {
             return new SuccessModel('登陆成功')
         }
         else{
             return new ErrorModel('登录失败!')
         }
    }

}

module.exports = handleUserRouter
 
app.js

const { resolve } = require('path')
const querystring = require('querystring')
const handleBlogRouter = require('./src/router/blog.js')
const handleUserRouter = require('./src/router/user.js')


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 serverHandle=(req,res)=>{
    // **** 设置返回格式为jason
    res.setHeader('content-type','application/json')

    const url = req.url
    req.path = url.split('?')[0]

    // **** 解析Query
    req.query = querystring.parse(url.split('?')[1])
   
    // **** 处理postData
    getPostData(req).then(postData=>{
        req.body=postData
       
         // **** 处理Blog 路由
        const blogData = handleBlogRouter(req,res)
        if (blogData){
            res.end(
                JSON.stringify(blogData)
            )
            return
        }
        // **** 处理user 路由
        const userData = handleUserRouter(req,res)
        if (userData){
            res.end(
                JSON.stringify(userData)
            )
            return
        }

        //***未命中路由 */
        res.writeHead(404,{"content-type":"text/plain"})
        res.write("404 not found\n")
        res.end()

    })

   

}


module.exports=serverHandle
 
package.json
 
{
  "name": "blog-1",
  "version": "1.0.0",
  "description": "",
  "main": "bin/www.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
 
 
 ******************* 上述未连数据库 ******************
https://dev.mysql.com/download/mysql 
https://dev.mysql.com/download/workbench 
 
 
npm install mysql --save --registry=https://registry.npm.taobao.org
 
如果要安装一个全局模块并使之生效
npm install -g cross-env
或cnpm install -g cross-env
然后:
在某个应用下,先删除node_Modules 目录及LOCK 文件; npm cache clear --force
Then:
 
 if no cross-env
          npm install cross-env --save-dev
          npm install
 if no nodemon  
         npm install nodemon --save-dev
         npm install
  
 
 
 
 
 
 
posted @   Hai-Zhong  阅读(59)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示