路由选择的核心是路由,顾名思义,路由指的就是我们要针对不同的url有不同的处理方式,例如处理/start的业务逻辑和处理/upload模块 的业务;逻辑就是不一致的。在现实的实现下,路由过程会在路由模块中“结束”,并且路由模块并不是真正者针对请求“采取行动”的模块,否则当我们的应用程 序变得更为复杂的时候就将无法得到很好的扩展。
这里我们首先创建一个叫做requesthandlers的模块,对于每一个请求处理程序都添加一个占位函数:
function start(){ console.log("request handler 'start' was called."); function sleep(milliseconds){ var starttime=new date().gettime(); while(new date().gettime()<starttime+milliseconds); } sleep(10000); return "hello start"; } function upload(){ console.log("request handler 'upload' was called."); return "hello upload"; } exports.start=start; exports.upload=upload;
这样我们就可以将请求处理程序和路由模块连接起来,让路由“有路可循”。之后我们确定将一系列请求处理程序通过一个对象来传递,并且需要使用松耦合的方式将这个对象注入到router()函数中,主文件index.js:
var server=require("./server"); var router=require("./router"); var requesthandlers=require("./requesthandlers"); var handle={}; handle["/"]=requesthandlers.start; handle["/start"]=requesthandlers.start; handle["/upload"]=requesthandlers.upload; server.start(router.route,handle);
如上所示,将不同的url映射到相同的请求处理程序上是容易的:只要在对象中添加一个键为“/”的属性,对应 requesthandlers.start即可。这样我们就可以简洁地配置/start和/的请求都交给start这一处理程序来处理。在完成看对象的 定义后,我们将它作为额外的参数传递给服务器,见server.js:
var http=require("http"); var url=require("url"); function start(route,handle){ function onrequest(request,response){ var pathname=url.parse(request.url).pathname; console.log("request for "+pathname+" received."); route(handle,pathname); response.writehead(200,{"content-type":"text/plain"}); var content=route(handle,pathname); response.write(content); response.end(); } http.createserver(onrequest).listen(8888); console.log("server has started."); } exports.start=start;
这样就在start()函数中添加了handle参数,并且把handle对象作为第一个参数传递给了route()回调函数,下面定义route.js:
function route(handle,pathname){ console.log("about to route a request for "+ pathname); if(typeof handle[pathname]==='function‘){ return handle[pathname](); }else{ console.log("no request handler found for "+pathname); return "404 not found"; } } exports.route=route;
通过以上代码,我们首先检查给定的路径对应的请求处理程序是否存在,如果存在则直接调用相应的函数。我们可以用从关联数组中获取元素一样的方式从 传递的对象中获取请求处理函数,即handle[pathname]();这样的表达式,给人一种感觉就像是在说“嗨,请你来帮我处理这个路径。”程序运 行效果如下图:
更多nodejs中实现路由功能。