# 结构
bin->www.jsmain
app.jsserver具体实现
//www.js
const serverHandle = require('../app.js')
const PORT = 8000
const server = http.createServer(serverHandle)
server.listen(PORT,() => {
console.log("OK");
})
//app.js
const serverHandle = (req, res) => {
//设置返回格式
res.setHeader('Content-type','application/json')
///下面部分先测试数据是否调通/
//设置返回数据
const returnData = {
name:"姓名",
title:"哈哈123",
// 获取当前开发环境
env:process.env.NODE_ENV
}
//返回数据
res.end(
JSON.stringify(returnData)
)
/
}
module.exports=serverHandle
# 初始化路由
| 描述 | 接口 | 方法 | 参数 | 备注 |
|---|---|---|---|---|
| 获取博客列表 | /api/blog/list | get | author作者,keyword关键字 | 参数为空则不进行查询过滤 |
| 获取一篇博客内容 | /api/blog/detail | get | id | |
| 新增一篇博客 | /api/blog/new | post | post中有新增的信息 | |
| 更新一篇博客 | /api/blog/update | post | id | postData中有更新的内容 |
| 删除一篇博客 | /api/blog/del | post | id | |
| 登录 | 单元格 | /api/user/login | post | postData中有用户名和密码 |
src->router->blog.js user.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: "这是获取博客详情的接口"
}
}
//新增一篇博客
if (method === "POST" && req.path === "/api/blog/new") {
return {
msg: "这是新增一篇博客的接口"
}
}
//更新一篇博客
if (method === "POST" && req.path === "/api/blog/update") {
return {
msg: "这是更新一篇博客的接口"
}
}
//删除一篇博客
if (req.method === "POST" && req.path === "/api/blog/del") {
return {
msg: "这是删除一篇博客的接口"
}
}
}
module.exports = handleBlogRouter
//app.js
const handleBlogRouter = require('./src/router/blog.js')
const handleUserRouter = require('./src/router/user.js')
const serverHandle = (req, res) => {
const url = req.url
req.path = url.split('?')[0]
//设置返回格式
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)
)
return
}
//未命中路由,返回404
res.writeHead(404,{"Content-type": "text/plain"})
res.write("404 Not Found\n")
res.end()
}
module.exports=serverHandle
# 完善路由层(router)数据层(controller)
# 创建数据模型
统一规定返回数据到客户端时,数据的格式保存一
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参数 (查看博客列表时需要作者author和keyword)
const querystring = require('querystring')
//将参数存放在req中的对象query中
req.query = querystring.parse(url.split('?')[1])
controller文件夹是用来存放控制获取数据的文件
src->controller->blog.js
// 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 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
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('更新博客失败')
}
# 删除和登录
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('删除博客失败')
}
const loginCheck = (username,password) => {
//先用假数据
if (username === 'zhangsan' && password === '123') {
return true
}
return false
}
module.exports = loginCheck
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