路由需要的信息,包括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/
看到相應的客戶端輸出:
?瀏覽器顯示:
?