接着上一篇完善路由
一、创建数据模型
作用:统一规定返回数据到客户端时,数据的格式保存一致
- 在src文件下创建model文件夹并在其目录下创建resModel.js文件
class BaseModel {
/*
data是返回到客户端的数据(对象类型),message是错误信息(字符串类型)
如果errno=0,请求成功 通过data来获取数据
如果errno=-1,请求失败 通过message来获取错误的具体原因
*/
constructor(data, message) {
//兼容(第一个参数(data)没有传递,只传递第二个参数)
if (typeof data === 'string'){
//将错误信息赋值给了message
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.errno = 0
}
}
//请求失败
class ErrorModel extends BaseModel {
constructor(data, message) {
super(data, message)
this.errno = -1
}
}
module.exports={
SuccessModel,
ErrorModel
}
二、优化查看博客列表
- 完善app.js文件(获取get参数)
//在原有代码基础上添加下面代码
//获取get参数 (查看博客列表时需要作者author和keyword)
const querystring = require('querystring')
//将参数存放在req中的对象query中
req.query = querystring.parse(url.split('?')[1])
- 在src目录下创建controller文件夹,并创建blog.js文件
原由:controller文件夹是用来存放控制获取数据的文件
// src/controller/blog.js
const getList = (author,keyword) => {
//先返回假数据(格式正确)
return [
{
id:1,
title:'标题A',
content:'内容A',
createTime:1546610491112,
author:'zhangsan'
},
{
id:2,
title:'标题B',
content:'内容B',
createTime:1546610524373,
author:'lisi'
}
]
}
module.exports = {
getList
}
- 完善获取博客列表的路由
// src/router/blog.js
const {getList} = require('../controller/blog.js')
const {SuccessModel,ErrorModel} = require('../model/resModel.js')
if (method === "GET" && req.path === "/api/blog/list") {
//获取请求数据 (req.query已经在app.js文件中已经保存好了)
const author = req.query.author || ''
const keyword = req.query.keyword || ''
//去请求博客列表数据
const listData = getList(author,keyword)
return new SuccessModel(listData)
}
- 测试
三、优化获取博客详情
- 在controller文件夹中的blog.js文件完善代码
const getDetail = (id) => {
//先返回假数据(格式正确)
return [
{
id:1,
title:'标题A',
content:'内容A',
createTime:1546610491112,
author:'zhangsan'
}
]
}
//在将方法其导出
- 完善获取博客详情的路由
// src/router/blog.js
if (method === "GET" && req.path === "/api/blog/detail") {
const id = req.query.id || ''
//去请求数据
const detail = getDetail(id)
return new SuccessModel(detail)
}
- 测试
接下来是解决post请求,但这里有一个小问题就是post发送的数据在服务端读取的时候是异步的,异常需要对其进行修改成同步的,具体解决方法点击这里
四、优化读取post data数据(Promise)
// app.js 重新创建一个函数用于处理post数据
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', chunk => {
if(!postData) {
resolve({})
return
}
resolve(JSON.parse(postData))
})
})
return promise
}
在app.js中的serverHandle函数调用该函数(先调用该函数,在进行路由转发)
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()
})
五、优化新建博客和更新博客
- 在controller文件夹中的blog.js文件完善代码
const newBlog = (blogData ={}) => {
//blogData 是一个博客对象,包含 title content 属性
return {
id:3 //表示新建博客,插入到数据库表里面的id
}
}
//在将方法其导出
- 完善新建博客的路由
//新增一篇博客
if (method === "POST" && req.path === "/api/blog/new") {
//获取post请求数据 (app.js中已经获取到了)
const postData = req.body
const id = newBlog(postData)
return new SuccessModel(id)
}
- 新增功能测试
接下来是更新功能,因为更新功能需要博客的id并且是该参数是添加在url中的,而前面的获取博客详情也是添加在url中,故可以在handleBlogRouter全局下去获取博客id
- 在controller文件夹中的blog.js文件完善代码
const updateBlog = (id,blogData ={}) => {
//id 就是要更新博客的 id
//blogData 是一个博客对象,包含 title content 属性
return true
}
//在将方法其导出
- 完善更新博客的路由
//更新一篇博客
if (method === "POST" && req.path === "/api/blog/update") {
//获取post请求数据 (app.js中已经获取到了)
const postData = req.body
const result = updateBlog(id, postData)
if(result) {
return new SuccessModel(result)
}
return new ErrorModel('更新博客失败')
}
- 更新功能测试
六、优化删除博客和登录
- 在controller文件夹中的blog.js文件完善代码
const delBlog = (id) => {
//id 就是要删除博客的 id
return true
}
//在将方法其导出
- 完善删除博客的路由
//删除一篇博客
if (req.method === "POST" && req.path === "/api/blog/del") {
const result = delBlog(id)
if (result) {
return new SuccessModel(result)
}
return new ErrorModel('删除博客失败')
}
- 在controller文件夹中的user.js文件完善代码
const loginCheck = (username,password) => {
//先用假数据
if (username === 'zhangsan' && password === '123') {
return true
}
return false
}
module.exports = loginCheck
- 完善登录的路由
// 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 postData = req.body
const {username,password} = postData
const result =loginCheck(username,password)
if (result) {
return new SuccessModel(result)
}
return new ErrorModel('登录失败')
}
}
module.exports = handleUserRouter
- 登录测试