上一节我们实现了简单的路由。本节我们实现了一个比较复杂的路由流程,统一管理。我们在server.js中初始化路由控件,启动脚本模块。varserver=require('./start');varrouter=require('./router');varrequestHandlers=require('./handlers');varhandler=[];handler["/"]=requestHandlers.home;handler["/show"]=requestHandlers.show;handler["/upload"]=requestHandlers.upload;server.start(router.route,handler);console.log("在端口1337上运行");启动脚本在server.js的最后,我们称之为启动模块,也就是start.js文件。在start.js文件中处理,代码如下varhttp=require('http');varurl=require('url');functionstart(route,handler){console.log("Starting~~");functiononRequest(req,res){varpathname=url.parse(req.url).pathname;var内容=路由(路径名,处理程序);if(content){res.writeHead(200,{"Content-Type":"text/plain"});res.write('确定');重发();}else{res.writeHead(404,{"Content-Type":"text/plain"});res.write("404未找到");重发();}}varport=process.env.port||1337;http.createServer(onRequest).listen(端口);console.log("开始了!!");}exports.start=开始;这里的核心代码是调用router(pathname,handler);此方法在路由器模块中实现。调用router模块中路由对应的方法,判断由参数pathname和handler组成的路径是否已经实现。如果是,则调用相应的路由方法,rou??ter.js代码如下如果(路径名==未定义)路径名=“/”;if(handler){if(typeofhandler[pathname]==='function'){handler[pathname]();返回真;}else{console.log("没有找到方法"+pathname);返回空值;}}else{console.log("NoMethodfoundinhandler");返回空值;}}exports.route=route;多种路由方法首先,我们需要定义多种路由方法。为了便于统一管控,我们将所有的路由处理方法写在一个handlers.js文件中,首先定义三个方法,这里只是实现最简单的打印功能home(){console.log("Request'home'调用。”);}functionshow(){console.log(“调用‘show’请求。”);}functionupload(){console.log(“调用‘upload’请求。”);}exports.home=主页;exports.show=显示;exports.upload=上传;最后我们在浏览器中输入http://127.0.0.1:1337/和http://127.0.0.1:1337/show,可以看到浏览器页面显示OK,命令行打印了相应的日志。项目中:1.server.js预定义路由方法,然后调用server启动方法(start.js)2.start.js负责启动服务,解析url传递的路径,将url传递给router.js。3、router.js判断路由是否正确,然后调用url对应的处理方法,在handlers.js中实现。4.handlers.js进行真正的路由处理。这样我们就手动实现了一个nodejs路由控制的例子。
