请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

老师,请你帮我看下代码,路由其他页面一直是404 not found,json没写错。

// 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}/)
})

正在回答 回答被采纳积分+3

1回答

双越 2019-06-03 20:56:24

先吧代码格式化一下吧,编辑器支持插入代码的功能。

0 回复 有任何疑惑可以回复我~
  • 提问者 iFlowers #1
    我在本地的代码是格式化的,粘贴到慕课网的平台就没了缩进。现在的问题是,get请求可以通过路由接收到,post全是404 not found。但是我通过postman又可以请求到两种形式的接口,奇怪不奇怪?
    回复 有任何疑惑可以回复我~ 2019-06-03 22:03:01
  • 双越 回复 提问者 iFlowers #2
    1. 以后无论从任何平台提问问题,代码一定要格式化,慕课网提交问题时是用 Markdown 形式编写内容,可以插入格式化的代码,需要你自己查一下(这一个善意的建议)。2. 按照你的描述,post 请求肯定走了 res.write(“404 not found\n”) 这一行,不符合预期,需要你在此打个断点跟踪一下,看看到底代码是怎么走到这一样的。
    回复 有任何疑惑可以回复我~ 2019-06-04 10:16:24
  • 提问者 iFlowers 回复 双越 #3
    我在那个位置打了个断点,但是调试不起来,然后把断点打到了前边,也就是const serverHandle = (req,res)那,但是发现进入了很多其他的地方,是不是我调试错了?
    回复 有任何疑惑可以回复我~ 2019-06-04 21:00:57
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信