上篇文章講到了瀏覽器中訪問 http://127.0.0.1:8888/ 輸出 "hello world", 但是實際當中, 用戶訪問的或許是 http://127.0.0.1:8888/start 異或者 http://127.0.0.1:8888/upload , 那么node.js該如何去針對不同的請求路徑(url) 做出不同的響應呢。
要做的事
1.構建一個路由模塊
模塊作用:提供請求的URL和其他需要的GET及POST參數,隨后根據這些數據來執行相應的代碼。因此,我們需要查看HTTP請求,從中提取出請求的URL以及GET/POST參數。
2.構建一個處理請求的程序模塊
模塊作用:存放不同的處理程序,和請求的URL相對應
3.將前面兩個模塊和http服務器結合起來
一、構建一個 路由 模塊
新建一個 router.js 寫入
// 路由模塊,針對不同的請求,做出不同的響應 // handle 處理請求方法 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;
二、構建一個處理請求的程序模塊
新建一個 requestHandlers.js 寫入
// 存放不同的處理程序,和請求的URL相對應 function start() { console.log("Request handler 'start' was called."); } function upload() { console.log("Request handler 'upload' was called."); } exports.start = start; exports.upload = upload;
三、將前面兩個模塊和http服務器結合起來
路由模塊的作用是:提供請求的URL和其他需要的GET及POST參數,隨后根據這些數據來執行相應的代碼。因此,我們需要查看HTTP請求,從中提取出請求的URL以及GET/POST參數。
我們需要的所有數據都會包含在request對象中,該對象作為onRequest()回調函數的第一個參數傳遞。但是為了解析這些數據,我們需要額外的Node.JS模塊,它們分別是url和querystring模塊。
在server.js里面分別引入
url模塊:解析url
querystring模塊: 解析GET和 POST請求帶的參數 (后面再說)
修改 server.js
// 請求(require)一個 nodejs 自帶的 http模塊 // 請求(require)一個 nodejs 自帶的 url解析模塊 var http = require("http"), url = require("url"); // console.log(url); // 調用 http模塊 提供的 createServer函數: // 返回一個對象,這個對象有一個 listen 方法,這個方法帶一個數值參數, // 指定這個 http 服務器監聽的端口號. function start(route, handle) { function onRequest(request, response) { // 獲取請求路徑 var pathname = url.parse(request.url).pathname; // 關閉nodejs 默認訪問 favicon.ico if (!pathname.indexOf('/favicon.ico')) { return; }; // 收到來自 pathname 的請求 console.log("Request for " + pathname + " received."); // 路由器處理 route(handle, pathname); // 返回數據 response.writeHead(200, {"Content-type": "text/plain"}); response.write("Hello world!"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has start!"); } // 開放接口 exports.start = start;
修改 index.js
var server = require("./server"), router = require("./router"), requestHandlers = require("./requestHandlers"); // handle 保存不同請求路徑對應的處理方法 var handle = {}; handle["/"] = requestHandlers.start; handle["/start"] = requestHandlers.start; handle["/upload"] = requestHandlers.upload; // 傳入路由模塊方法, 路徑處理方法 server.start(router.route, handle);
四、測試
在 command 面板輸入 node index.js
瀏覽器訪問 http://127.0.0.1:8888/start command 面板顯示
整個過程中有個插曲,就是我測試的時候 command面板 每次都會輸出一次 訪問 /favicon.ico 的記錄,然后百度得到了屏蔽的方法
http://cnodejs.org/topic/529be564a6957a0809408cab
在 server.js 中插入
// 關閉nodejs 默認訪問 favicon.ico if (!pathname.indexOf('/favicon.ico')) { return; };