第一个函数是app.js,我在getPostData写了一个console.log,在解析query写了一个console.log
const querystring = require('querystring')
const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')
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
}
console.log("promise执行")//老师我在这里做了一个标记
resolve(
JSON.parse(postData)
)
})
})
return promise
}
const serverHandle = (req,res) => {
//设置返回格式
res.setHeader('Content-type','application/json')
//获取path
const url = req.url
// path = url.split('?')[0]
req.path = url.split('?')[0]
//解析query
req.query = querystring.parse(url.split('?')[1])
getPostData(req).then(postData => {
req.body = postData
console.log("req.body:" ,req.body)老师我在这里做了一个标记
})
//处理 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中的blog.js,我在新建博客哪里输出了一个console.log
const { getList, getDetail, newBlog } = require('../controller//blog')
const { SuccessModel, ErrorModel} = require('../model/resModel')
const handleBlogRouter = (req, res)=>{
const method = req.method
//获取博客列表
if (method === 'GET' && req.path === '/api/blog/list') {
const author = req.query.author || ''
const keyword = req.query.keyword || ''
const listData = getList(author, keyword)
return new SuccessModel(listData)
}
//获取博客详情
if (method === 'GET' && req.path === '/api/blog/detail') {
const id = req.query.id || ''
const data = getDetail(id)
return new SuccessModel(data)
}
//新建一篇博客
if (method === 'POST' && req.path === '/api/blog/new') {
console.log("在接口中",req.body)//我在这里做了一个标记
const data = newBlog(req.body)
return new SuccessModel(data)
}
//更新一篇博客
if (method === 'POST' && req.path === '/api/blog/update') {
return {
msg: '这是更新博客的接口'
}
}
//删除一篇博客
if (method === 'POST' && req.path === '/api/blog/del') {
return {
msg: '这是删除博客的接口'
}
}
}
module.exports = handleBlogRouter
这个是controller中的blog.js
const getList = (author,keyword) => {
return [
{
id: 1,
title: '标题A',
content: '内容A',
createTime: 1593672088092,
author: 'zhangsan'
},
{
id: 2,
title: '标题B',
content: '内容B',
createTime: 1593672088100,
author: 'lisi'
}
]
}
const getDetail = id => {
return {
id: 1,
title: '标题A',
content: '内容A',
createTime: 1593672088092,
author: 'zhangsan'
}
}
const newBlog = (blogData = {}) => {
console.log('blogData:', blogData)//输出post的数据信息
return {
id:3
}
}
module.exports = {
getList,
getDetail,
newBlog
}
执行结果截图:
这个正常
这里明显先执行的newblog再执行的读取数据,不知道为什么?