nodejs中实现路由功能

2020-06-17 05:41:18易采站长站整理

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]();这样的表达式,给人一种感觉就像是在说“嗨,请你来帮我处理这个路径。”程序运 行效果如下图: