我們接著改造伺服器,讓請求處理函式能夠回傳一些有意義的內容。
來看看怎麼實作:
1、讓請求處理函式透過 onRequest 函式直接 return 它們要展示給使用者的內容。
2、從「讓請求處理函式回傳需要在瀏覽器顯示的內容」開始著手。
我們需要把 requestHandler.js 改成如下形式:
代碼如下:
function start() {
console.log("Request handler 'start' was called.");
return "Hello Start";
}
function upload() {
console.log("Request handler 'upload' was called.");
return "Hello Upload";
}
exports.start = start;
exports.upload = upload;
同樣地,請求路由需要把請求處理函式回傳給它的內容再回傳給伺服器。因此我們把 router.js 改成:
代碼如下:
function route(handle, pathname) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
return handle[pathname]();
} else {
console.log("No request handler found for " + pathname);
return "404 Not found";
}
}
exports.route=route;
如上述程式碼所示,當請求無法被路由時,我們也回傳了相關的錯誤資訊。
最後,我們要重構 server.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.");
response.writeHead(200, {"Content-Type": "text/plain"});
var content = route(handle, pathname);
response.write(content);
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start=start;
運行重構後的應用:
請求 https://localhost:8888/start,瀏覽器會輸出「Hello Start」,
請求 https://localhost:8888/upload 會輸出「Hello Upload」,
而請求 https://localhost:8888/foo 會輸出「404 Not found」。
這樣的效果很不錯。下一節我們要來認識一個概念:阻塞操作。