路由,顾名思义,是指我们要针对不同的URL有不同的处理方式。例如处理/start的“业务逻辑”就应该和处理/upload的不同。
在现在的实现下,路由过程会在路由模块中“结束”,并且路由模块并不是真正针对请求“采取行动”的模块,否则当我们的应用程序变得更为复杂时,将无法很好地扩展。
我们暂时把作为路由目标的函数称为请求处理程序。现在我们不要急着来开发路由模块,因为如果请求处理程序没有就绪的话,再怎么完善路由模块也没有多大意义。
requestHandlers的模块
应用程序需要新的部件,因此加入新的模块 -- 已经无需为此感到新奇了。我们来创建一个叫做requestHandlers的模块,并对于每一个请求处理程序,添加一个占位用函数,随后将这些函数作为模块的方法导出:
requestHandlers的模块,并对于每一个请求处理程序,添加一个占位用函数,随后将这些函数作为模块的方法导出:
requestHandlers.js
- function start() {
- console.log("Request handler 'start' was called.");
- }
- function upload() {
- console.log("Request handler 'upload' was called.");
- }
- exports.start = start;
- exports.upload = upload;
router模块
通过检查给定的路径对应的请求处理程序是否存在,如果存在的话直接调用相应的函数
router.js
- function route(handle, pathname) {
- console.log("About to route a request for " + pathname);
- if (typeof handle[pathname] === 'function') {
- handle[pathname]();
- } else {
- console.log("No request handler found for " + pathname);
- }
- }
- exports.route = route;
server模块
处理请求模块
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);
- //在这里我们就可以对不同的路径进行不同处理
- //if(pathname=="") response.writeHead不同的信息之类的
- 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;
index模块
启动模块,主模块
index.js
- var server = require("./server");
- var router = require("./router");
- var requestHandlers = require("./requestHandlers");
- //区分大小写的
- var handle = {}
- handle["/"] = requestHandlers.start;
- handle["/start"] = requestHandlers.start;
- handle["/upload"] = requestHandlers.upload;
- server.start(router.route, handle);
运行后效果
如果现在启动应用(node index.js,始终记得这个命令行),随后请求一个URL,我请求的分别是是http://localhost:8888/,http://localhost:8888/start,http://localhost:8888/start1,你将会看到应用输出相应的信息,这表明我们的HTTP服务器已经在使用路由模块了,并会将请求的路径传递给路由,路由再找到对应的处理函数:


