您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

nodejs中实现路由功能

2024/3/28 8:18:09发布25次查看
初学node,发现了与自己之前的观点完全不同的场面——你眼中的javascript,是干什么用的呢?特效?or 只是与客户端的交互?可以说,javascript最早是运行在浏览器中的,然而你要这样想,浏览器只是你提供了一个上下文(context),它定义了 使用javascript可以做什么,这里可以想成类似的一个企业,企业定义了你可以在这里做什么,但是并没有说太多关于javascript语言本身可 以做什么。事实上,作为一门完整的语言,javascript可以使用在不同的上下文中,体现出不同的能力。这里所讲到的nodejs其实说白了就是提供 的一个上下文,一个运行环境,它允许在后端(脱离浏览器环境)来运行javascript代码。
路由选择的核心是路由,顾名思义,路由指的就是我们要针对不同的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中实现路由功能。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product