node.js routing - 这里实际发生了什么

时间:2017-04-15 15:19:02

标签: 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", 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

路径路径= /完成

服务器已于9999开始。

当我点击http://localhost:9999/finish时,我在控制台中找到了:

要求/收到结束。

主路径名= /完成

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

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

让我们看看以下一行:

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

它似乎与for属性无关。

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

1 个答案:

答案 0 :(得分:0)

因为它是在路由变量中定义的,现在你正在调用它。

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

第二部分是onRequest方法,您可以在其中检查应用中是否存在请求的网址。并根据请求的URL调用相应的方法,然后使用404进行响应。

PS:逻辑很好,但它不处理请求类型GETPOSTPUT等。

相关问题