const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')
const querystring = require('querystring')
const serverHandle = (req, res) => {
//获取path
const url = req.url
req.path = url.split('?')[0]
req.query = querystring.parse(url.split('?')[1])
const getPostData = (req) => {
const promise = new Promise((resolve, reject) => {
if (req.method === 'POST' && req.headers['content-type'] === 'application/json') {
let postData = ''
req.on('data', (trunk) => {
//这里没有进去
console.log('get some data')
postData += trunk.toString()
})
req.on('end', () => {
if (!postData) {
resolve({})
return
}
//将postData转化为对象格式
resolve(JSON.parse(postData))
})
}
else {
resolve({})
}
})
return promise
}
// 设置返回格式为 JSON
res.setHeader('Content-type', 'application/json')
getPostData(req)
.then(postData => {
//将postdata放入req
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
}
res.writeHead(404, { 'Content-type': 'text/plain' })
res.write('404 NOT FOUND')
res.end()
}
module.exports = serverHandle
补充:
我把处理基本上都注释掉之后发现运行的顺序出了问题
登录后可查看更多问答,登录/注册