node.js路由-这里到底发生了什么

node.js路由-这里到底发生了什么,node.js,url-routing,Node.js,Url Routing,这是一个带有路由的简单节点应用程序。代码如下: var http = require("http"); var url = require("url"); var route = { routes:{}, for:function(path, handler){ console.log("route path = "+path); this.routes[path]= handler; } }; route.for("/start

这是一个带有路由的简单节点应用程序。代码如下:

var http = require("http");
var url = require("url");

var route = {
    routes:{},
    for:function(path, handler){

        console.log("route path = "+path);
        this.routes[path]= handler; 
    }

};

route.for("/start", function(request, response){

    response.writeHead(200,{"Content-Type":"text/plain"});

    response.write("Hello");
    response.end();
});

route.for("/finish", function(request, response){

    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Goodbye");
    response.end();
});

function onRequest(request, response) {

    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");
    if(typeof route.routes[pathname] ==='function'){

       console.log(" main pathname = "+pathname);
       route.routes[pathname](request, response);
   }else{
       response.writeHead(404, {"Content-Type": "text/plain"});
       response.end("404 Not Found");
     }

}// END OF ONrEQUEST

http.createServer(onRequest).listen(9999);
console.log("Server has started at 9999.");
当我运行应用程序时,我在控制台中看到:

路由路径=/start

路由路径=/finish

服务器已在9999启动

当我点击时,我在控制台中发现:

请求/完成已收到

主路径名=/finish

我试图理解代码-首先构建
route
对象变量

Q1)for的
属性在那里是如何工作的

让我们看看下面这行:

route.for("/start", function(request, response){
它似乎以任何方式与
属性的
相关


Q2)它与
属性的
有什么关系?

因为它是在route变量中定义的,现在您正在调用它

它在
route
变量中定义为属性,您正在调用此属性(基本上是函数)并将路由存储在其中

第二部分是
onRequest
方法,您可以在其中检查应用程序中是否存在请求的URL。并根据请求的URL调用相应的方法,以
404
响应


PS:逻辑很好,但它不处理请求的类型
GET
POST
PUT
等。

因为它是在
route
变量中定义的,现在您正在调用它。简单,真的。。。在回答表单中而不是注释中?那么为对象属性设置值的规则是什么呢?@IstiaqueAhmed将另一个参数传递给
for
函数,并像
GET
POST
一样存储它,并在请求时检查调用了哪一个。可能这不是我在注释中要求的。我不明白,你想详细说明一下吗?设置对象属性只是
obj.propertyName='value'
,如果你问这个问题。
不是
route
的属性吗
obj.propertyName='value'
不适用于此处。