伺服器需要依據不同的 URL 或請求來執行不同的操作,這可以透過路由來實現。
第一步得先解析出請求 URL 的路徑,這裡我們引入 url 模組。
我們來替 onRequest() 函式加上一些邏輯,用來找出瀏覽器請求的 URL 路徑:
代碼如下:
var http = require("http");
var url = require("url");
function start() {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
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;
好了,pathname 就是請求的路徑,我們可以用它來區分不同請求,如此便能對來自 /start 與 /upload 的請求使用不同的程式碼處理。
接著來寫路由,建立一個名為 router.js 的檔案,程式碼如下:
代碼如下:
function route(pathname) {
console.log("About to route a request for " + pathname);
}
exports.route = route;
這段程式碼目前什麼都沒做,我們先把路由與伺服器整合起來。
接著擴充伺服器的 start() 函式,在其中運行路由函式,並把 pathname 當參數傳給它。
代碼如下:
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);
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.js,讓路由函式能被注入到伺服器中:
代碼如下:
var server = require("./server");
var router = require("./router");
server.start(router.route);
運行 index.js,隨便造訪一個路徑(例如 /upload),就會發現主控台輸出了「About to route a request for /upload.」。
這代表我們的 HTTP 伺服器與請求路由模組已經能彼此溝通了。
下一節我們將實作:針對不同的 URL 請求給予不同的回饋。