老师,请你帮我看下代码,路由其他页面一直是404 not found,json没写错。
来源:5-6 初始化路由
iFlowers
2019-06-03
// app.js
const handleBlogRouter = require("./src/router/blog")
const handleUserRouter = require("./src/router/user")
const serverHandle = (req, res) => {
//设置JSON格式
res.setHeader(“Content-type”, “application/json”)
//获取path
const url = req.url
req.path = url.split("?")[0]
const path = req.path
//处理 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
//blog.js
const handleBlogRouter = (res,req) => {
const method = req.method
//获取博客列表
if (method === ‘GET’ && path === ‘/api/blog/list’) {
return {
msg: ‘这是获取博客列表的接口’
}
}
//获取列表详情
if (method === ‘GET’ && path === ‘/api/blog/detail’) {
return {
msg: ‘这是获取博客详情的接口’
}
}
//新建博客
if (method === ‘POST’ && path === ‘/api/blog/new’) {
return {
msg: ‘这是新建博客的接口’
}
}
//更新博客
if (method === ‘POST’ && path === ‘/api/blog/update’) {
return {
msg: ‘这是更新博客的接口’
}
}
//删除博客
if (method === ‘POST’ && path === ‘/api/blog/delete’) {
return {
msg: ‘这是删除博客的接口’
}
}
}
module.exports = handleBlogRouter
// www.js
const http = require(“http”)
const HOSTNAME = ‘127.0.0.1’
const PORT = 8000
const serverHandle = require(’…/app’)
const server = http.createServer(serverHandle)
server.listen(PORT, () => {
// 这里我用了模板字符串语法
console.log(Server running at http://${HOSTNAME}:${PORT}/
)
})
1回答
-
双越
2019-06-03
先吧代码格式化一下吧,编辑器支持插入代码的功能。
042019-06-05
相似问题