01——开发博客项目之接口02

1.搭建开发环境
2.初始化路由

1.搭建开发环境

  • 从0开始搭建,不使用任何框架
  • 使用nodemon 监测文件变化,自动重启 node
  • 使用 cross-env 设置环境变量,兼容mac linux 和windows

安装 cross-env

npm install --save-dev cross-env

文件目录
在这里插入图片描述
package.json

{
  "name": "blog",
  "version": "1.0.0",
  "description": "",
  "main": "app.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",
  "devDependencies": {
    "cross-env": "^7.0.2"
  }
}

注意script中dev与pro,通过cross-env 配置了环境变量
app.js

const serverHandle = (req, res) => {
    // 设置返回格式 JSON
    res.setHeader('Content-type', 'application/json')

    const resData = {
        name: "wayliu",
        site: "zhuhai",
        // process 顾名思义就是进程
        //该对象表示Node所处的当前进程,允许开发者与该进程互动
        env: process.env.NODE_ENV
    }

    res.end(
        JSON.stringify(resData)
    )
}

module.exports = serverHandle

通过process.env.NODE_ENV获取环境变量

bin/www.js

const http = require('http')

const PORT = 3000
const serverHandle = require('../app')

const server = http.createServer(serverHandle)
server.listen(PORT)

通过app.js中serverHandle创建server并开启监听端口

2.初始化路由

在这里插入图片描述

文件目录

在这里插入图片描述
router/blog.js

const handleBlogRouter = (req, res) => {
    const method = req.method  //GET/POST
    const url = req.url
    const path = url.split('?')[0] // 获取路由

    // 获取博客列表
    if (method === 'GET' && path ==='/api/blog/list') {
        return {
            msg: '这是获取博客列表的接口'
        }
    }

    // 获取博客详情
    if (method === 'GET' && path ==='/api/blog/detail') {
        return {
            msg: '这是获取博客详情的接口'
        }
    }

    // 新建一篇博客
    if (method === 'POST' && path ==='/api/blog/new') {
        return {
            msg: '这是新建博客的接口'
        }
    }

    // 更新一篇博客
    if (method === 'POST' && path ==='/api/blog/update') {
        return {
            msg: '这是更新博客的接口'
        }
    }

    // 删除一篇博客
    if (method === 'POST' && path ==='/api/blog/delete') {
        return {
            msg: '这是删除博客的接口'
        }
    }
}

module.exports = handleBlogRouter

router/user.js

const handleUserBlog = (req, res) => {
    const method = req.method  //GET/POST
    const url = req.url
    const path = url.split('?')[0] // 获取路由

    // 登陆
    if (method === 'POST' && path === '/api/user/login') {
        return {
            msg: '这是登陆的接口'
        }
    }
}

module.exports = handleUserBlog

app.js

const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')

const serverHandle = (req, res) => {
    // 设置返回格式 JSON
    res.setHeader('Content-type', 'application/json')

    // 处理 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)
        )
    }

    // 未命中路由返回404
    res.writeHead(404, {"Content-type": "text/plain"})
    res.write("404 not Found\n")
    res.end()
}

module.exports = serverHandle

通过在app.js中引入两个路由文件进行相应的路由出路,另外配置了404

优化
由于两个路由文件都用到了

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

可以在app.js中全局声明

const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')

const serverHandle = (req, res) => {
    // 设置返回格式 JSON
    res.setHeader('Content-type', 'application/json')
    // 获取path
    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
    }

    // 未命中路由返回404
    res.writeHead(404, {"Content-type": "text/plain"})
    res.write("404 not Found\n")
    res.end()
}

module.exports = serverHandle

// 获取path
const url = req.url
req.path = url.split(’?’)[0] // 获取路由

把两个路由中的path改为req.path。
如user.js

const handleUserBlog = (req, res) => {
    const method = req.method  //GET/POST
    
    // 登陆
    if (method === 'POST' && req.path === '/api/user/login') {
        return {
            msg: '这是登陆的接口'
        }
    }
}

module.exports = handleUserBlog
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值