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

1.处理postData
2.新建博客接口

1.处理postData

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

// 用于处理 post data
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) => {
    // 设置返回格式 JSON
    res.setHeader('Content-type', 'application/json')
    // 获取path
    const url = req.url
    req.path = url.split('?')[0] // 获取路由

    // 解析 query
    req.query = querystring.parse(url.split('?')[1])

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

module.exports = serverHandle

// process 顾名思义就是进程
//该对象表示Node所处的当前进程,允许开发者与该进程互动
// env: process.env.NODE_ENV
  1. 用于处理 post data=>getPostData()
  2. 调用getPostData(),把resolve里的参数赋值给req.body,包裹blog路由和user路由,使他们能使用req.body
    对照注释

2.新建博客接口

接口路由
router/blog.js

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

新建博客处理逻辑
controller/blog.js

// 新建博客处理逻辑
// blogData = {} blogData没有值时默认为空
const newBlog = (blogData = {}) => {
    // blogData 是一个博客对象,包含title content 属性
    console.log('newBlog blogData...',blogData)
    return {
        id: 3 
    }
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值