標籤:style blog http color io os 使用 java ar
路由需要的資訊,包括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/
看到相應的用戶端輸出:
瀏覽器顯示:
node.js-------使用路由模組