Node系列学习之Node基础(三)

216 阅读2分钟

这是我参与更文挑战的第9天,活动详情查看:更文挑战

本文是Node学习系列第三篇文章,接上篇文章续写,基本完成了路由处理,学会使用Node开发接口~

接上篇文章: Node系列学习之Node基础(二), 上篇中只是处理了 /api/blog/list 这个接口,另一个 get请求并未处理,现在简单处理一下.

controller/blog.js

...
const getDetail = id => {
  return {
    id: 1,
    title: '标题XXX',
    content: '内容A',
    createTime: 1623165670787,
    author: 'Tmier1'
  }
}
module.exports = {
  ...
  getDetail
}

router/blog.js

const { getList, getDetail } = require('../controller/blog')
...
 // 获取博客详情
if (method == 'GET' && req.path == '/api/blog/detail') {
    const id = req.query.id
    const data = getDetail(id)
    return new SuccessModel(data)
}

image-20210609223651702

OK了,GET 请求目前简单搞定,然后下面就主要处理 POST 请求。

封装方法

简单封装一下处理post请求数据的方法

app.js

// 用于处理 postData
const getPostData = req => {
  return new Promise((resolve, reject) => {
    if (req.method !== 'POST') {
      resolve({})
      return
    }
    // 非json数据类型,忽略并返回{}
    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))
    })
  })
}

然后将拿到的postData 放入 req.body, 完整 app.js如下:

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

// 用于处理 postData
const getPostData = req => {
  return new Promise((resolve, reject) => {
    if (req.method !== 'POST') {
      resolve({})
      return
    }
    // 非json数据类型,忽略并返回{}
    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))
    })
  })
}

const serverHandle = (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])

  // 处理 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
    }
    // 未命中路由, 返回404
    res.writeHead(404, { 'Content-Type': 'text/plain' })
    res.write('404 Not Found\n')
    res.end()
  })
}
module.exports = serverHandle

新建博客

controller/blog.js

模拟下数据,暴露方法

...
const newBlog = (blogData = {}) => {
  return {
    id: 3
  }
}
...
module.exports = {
  ...
  newBlog,
}

router/blog.js

const { getList, getDetail, newBlog, updateBlog} = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
...
// 新建一篇博客
if (method == 'POST' && req.path == '/api/blog/new') {
    const data= newBlog(req.body)
    return new SuccessModel(data)
}

更新博客

controller/blog.js

...
const updateBlog = (id,blogData= {}) => {
  return true
}
module.exports = {
  ...
  updateBlog
}

router/blog.js

const id = req.query.id
// 更新一篇博客
if (method == 'POST' && req.path == '/api/blog/update') {
    const result = updateBlog(id,req.body)
    if(result) {
        return new SuccessModel()
    } else {
        return new ErrorModel('更新博客失败~')
    }
}

删除博客

controller/blog.js

const delBlog = (id) => {
  // id: 要删除博客的ID
  return true
}
...
module.exports = {
  ...
  delBlog
}

router/blog.js

// 删除一篇博客
if (method == 'POST' && req.path == '/api/blog/del') {
    const result = delBlog(id)
    if (result) {
        return new SuccessModel()
    } else {
        return new ErrorModel('删除博客失败~')
    }
}

登录接口

crotroller 文件夹下新建 user.js 来处理登录接口返回数据

croller/user.js

const loginCheck = (username, password) => {
  if(username == 'lll' && password == '666') {
    return true
  }
  return false
}
module.exports = {
  loginCheck
}

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
    const result = loginCheck(username,password)
    if(result) {
      return new SuccessModel()
    }
    return new ErrorModel('登录失败~')
  }
}
module.exports = handleUserRouter

OK,到这就算把路由处理完成了~ 这里面的路由处理大同小异,多写多练几次就好了,用Node写接口就是舒服~