node博客开发之路由管理
在这里主要讲解的就是对于路由的管理,在进行项目开发时,遵守的必定是模块化开发,这样做的好处就是更加容易的管理。在这里我们将 const server = http.createServer((req,res) => {})中的(req,res) => {}单独的分离了出来在另外一个文件中做处理。这样在入口文件中处理的就是业务逻辑上的代码,分离出来的就是技术逻辑上的代码。
在处理路由中我要将此博客开发的路由分为两个部分,第一个与博客有关的,第二个与用户有关的。可以这样来理解,如果在处理路由时有几个端口我们就需要在后台搭建的时候建几个文件,每一个文件都是去处理与之对应的端口。 因此在这里我们先需要来跑通路由。那么下面就是对于博客路由处理部分的代码,代码如下:
const handleBlogRouter = (req,res) => {
const method = req.method; //获取请求方式
if(method === 'GET' && req.path === '/api/blog/list'){
return {
mes: '这是获取博客列表的接口'
}
}
if(method === 'GET' && req.path === '/api/blog/detail'){
return {
mes: '这是获取博客详情的接口'
}
}
if(method === 'POST' && req.path === '/api/blog/new'){
return {
mes: '这是获取博客新建的接口'
}
}
if(method === 'POST' && req.path === '/api/blog/delete'){
return {
mes: '这是删除博客列表的接口'
}
}
if(method === 'POST' && req.path === '/api/blog/update'){
return {
mes: '这是更新博客列表的接口'
}
}
}
module.exports = handleBlogRouter;
然后以同样的方式来处理与用户相关的路由,代码如下:
const handleUserRouter = (req,res) =>{
const method = req.method;
// const url = req.url;
// const path = url.split('?')[0];
if(method === 'POST' && req.path === '/api/user/login'){
return{
mes: '这是用户登录的接口'
}
}
}
module.exports = handleUserRouter;
最后在app.js文件中导入这两个方法然后再在这个文件里面,对数据进行处理
const handleUserRouter = require('./src/router/user');
const handleBlogRouter = require('./src/router/blog');
const serverHandle = (req,res) => {
//设置返回JSON的格式
res.setHeader('Content-type','application/json');
//代码优化
const url = req.url; //获取请求url
req.path = url.split('?')[0]; //获取路由
const blogData = handleBlogRouter(req,res);
const userData = handleUserRouter(req,res);
if(blogData){
res.end(
JSON.stringify(blogData)
)
return
}
if(userData){
res.end(
JSON.stringify(userData)
)
return
}
//未命中路由就执行下面的操作
res.writeHead(404,{"Content-type" : "text/plain"});
res.write("404 Not Found\n");
res.end()
}
module.exports = serverHandle;
最后再将这个导出的文件放入到入口文件当中,即const server = http.createServer(serverHandle),就可以跑通整个的路由部分。对于博客的管理其实质就是如何去处理get与post请求。这个在https://blog.csdn.net/care_yourself/article/details/101062497中已经说过了,在这里管理博客部分最主要的就是如何对路由进行管理,即命中路由应该返回什么结果,未命中路由又应该返回怎样的结果。