node博客之路由搭建

项目列表

在这里插入图片描述

www.js

const http = require('http')
const PORT = 9000
const serverHandle = require('../app.js')

const server = http.createServer(serverHandle)

server.listen(PORT)
console.log('OK')

blog.js

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


    // 列表的接口
    if (method === 'GET' && req.path === '/api/blog/list') {
        return {
            msg: '我是博客列表的接口'
        }
    }
    // 博客详情
    if (method === 'GET' && req.path === '/api/blog/detail') {
        return {
            msg: '我是博客详情的接口POST'
        }
    }
    //新建一条博客
    if (method === 'POST' && req.path === '/api/blog/new') {
        return {
            msg: '我是新建一条博客'
        }
    }
    //更新一条博客
    if (method === 'POST' && req.path === '/api/blog/update') {
        return {
            msg: '我是更新一条博客'
        }
    }
    //删除一条博客
    if (method === 'POST' && req.path === '/api/blog/del') {
        return {
            msg: '我是删除一条博客'
        }
    }
}
module.exports = handleBlogRouter;

user.js

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

    //新建一条博客
    if (method === 'POST' && req.path === '/api/user/login') {
        return {
            msg: '我是登陆的接口'
        }
    }
}
module.exports = handleUserRouter;

app.js

const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')
const serverHandle = (req,res)=>{
    //         env:process.env.NODE_ENV
    res.setHeader('Content-type','application/json');
    const url = req.url;
    req.path = url.split('?')[0]
    // 处理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",
  "bin": {
    "blog-1": "www.js"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev":"cross-env NODE_ENV=dev nodemon ./bin/www.js",
    "prd":"cross-env NODE_ENV=production nodemon ./bin/www.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cross-env": "^7.0.3",
    "nodemon": "^2.0.7"
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值