nodejs基础 -- 路由

我们要为路由提供请求的URL和其他需要的GET/POST参数,随后路由需要根据这些数据(URL、GET/POST参数)来执行相应的代码。

因此,需要查看HTTP请求,从中提取出请求的URL及GET/POST参数。(这一功能属于路由还是服务器?暂无定论,这里暂定为HTTP服务器的功能)。这些数据(url,get/post参数)都包含在request对象中,而该对象是作为onRequest()回调函数的第一个参数传递的。

总结以上:

首先,我们需要查看HTTP请求,从中提取出URL及GET/POST参数,然后路由就可以根据这些残血来执行相应的代码。

示例:

1、创建server.js服务器文件,内容如下:

var http = require("http");
var url = require("url"); //引入url原生模块,用来解析request中带的url及get/post参数

function start(route){
    function onRequest(request,response){
        var pathname = url.parse(request.url).pathname; //通过url对象解析路径
        console.log("Request for"+pathname+"received.");
        
        route(pathname);
        
        response.writeHead(200,{"content-type":"text/plain"});
        response.write("hello world");
        
        response.end();
    }
    
    http.createServer(onRequest).listen(8888);
    console.log("server has started...");
}

exports.start = start;

2、建立router.js路由文件,内容如下:

function route(pathname){
    console.log("about to route a request for"+pathname);
}

exports.route = route;

3、建立调用入口文件index.js,内容如下:

var server = require("./server");
var router = require("./router");

server.start(router.route);

运行index.js文件,结果如下:

原文地址:https://www.cnblogs.com/hf8051/p/5056360.html