標籤:style blog http color io java ar for div
路由,就是不同的URL有不同的處理方式,例如/start的“商務邏輯”和/upload的不同。
在現在的現實下,路由過程會在路由模組中“結束”,並且路由模組並不是真正針對請求採取行動的處理常式模組,所以,當處理常式變更時,需要修改的內容不用涉及到路由。
通常在請求處理常式就緒的時候設定路由。
當應用程式需要新的組件,就需要加入新的模組。可以建立一個requestHandlers的模組,並對每一請求處理常式,添加一個佔位函數,隨後這些佔位函數作為模組匯出。
下面是一個例子:
------requestHandlers.js
------router.js
------server.js
------index.js
requestHandlers.js
/*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.js
/*router模組*//*檢查URL中給定路徑對應的請求處理常式是否存在,如果存在直接調用相應函數*/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.js
/*server模組*//*請求處理模組,從URL中取出路徑,並交由router.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不同的資訊之類的if(pathname=="/"){response.writeHead(200,{"Content-Type":"text/plain"});response.write("pathname: /");response.end();}if(pathname=="/start"){response.writeHead(200,{"Content-Type":"text/plain"});response.write("pathname: /start");response.end();}if(pathname=="/upload"){response.writeHead(200,{"Content-Type":"text/plain"});response.write("pathname: /upload");response.end();}}http.createServer(onRequest).listen(3000);console.log("Server has started");}
index.js
/*index 模組*//*啟動模組,主模組,handle集合對象裡面,是pathname與處理函數組成的數組元素集合,這個集合也是router.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://127.0.0.1:3000
控制台顯示:
瀏覽器顯示:
在瀏覽器輸入以下URL請求:
http://127.0.0.1:3000/start
控制台顯示:
瀏覽器顯示:
在瀏覽器輸入以下URL請求:
http://127.0.0.1:3000/upload
控制台顯示:
瀏覽器顯示:
在瀏覽器輸入以下URL請求:
http://127.0.0.1:3000/start1
控制台顯示:
node.js-------路由後添加處理函數