node.js-------使用路由模块

 

路由需要的信息,包括URL 及GET 或 POST参数。路由根据这些参数执行相应的js处理程序,因此,需要在HTTP请求中提取出URL以及GET或POST参数。这些请求参数在request对象中,这个对象是onRequest()回调函数的第一个参数。需要提取这些信息,需要Node.js的模块,url和querystring模块。

                url.parse(string).query

                         |

     url.parse(string).pathname    |

              |           |  

 http://localhost:8888/start?foo=bar&hello=world                                  

    querystring(string)["foo"]

                querystring(string)["hello"]

当然可以用querystring模块来解释POST请求体中的参数。

可以通过不同的请求的URL路径来映射到不同的处理程序上面,路由就是做这一个工作。

例如来自:/start和/upload的请求可以使用不同的程序来处理。

下面是一个例子:

---index.js

---server.js

---route.js

编写一个路由,route.js

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

 编写处理请求的页面,server.js

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

function start(route){
	function onRequest(request, response){
		var pathname = url.parse(request.url).pathname;
		console.log("Request for " + pathname + "received");
		
		route(pathname);
		//在这里可以对不同的路径进行处理
		//if(pathname =="...") response.writeHead不同的信息之类
		response.writeHead(200, {"Content-Type" : "text/plain"});
		response.write("Hello World");
		response.end();
	}
	
	http.createServer(onRequest).listen(3000);
	console.log("Server has started.");
}
exports.start = start;

编写启动文件,index.js

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

server.start(router.route);

在客户端启动应用,服务器启动,开始监听3000端口:

node index.js

在浏览器端输入一个请求URL:

http://127.0.0.1:3000/

看到相应的客户端输出:

 浏览器显示:

原文地址:https://www.cnblogs.com/IanI/p/3990210.html