almost 10 years ago
有了基本的HTTP Server後,我們接下來就要處理路徑(route)問題
為了解析路徑,除了本身的http模組,我們還需要url模組
建立一個 03-http_route.js 的檔案 (接續02-basic_http_hello_world.js)
var server,
ip = "127.0.0.1",
port = 1337,
http = require('http'),
url = require('url');
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
response.writeHead(200, {"Content-Type": "text/plain"});
switch (pathname) {
case "/index":
response.end('I am index.\n');
break;
case "/test":
response.end('this is test page.\n');
break;
default:
response.end('default page.\n');
break;
}
}
http.createServer(onRequest).listen(port, ip);
console.log("Server has started.");
command line打node 03-http_route.js
再打開瀏覽器:輸入以下四種網址,頁面會有不同結果(終端機也會有不同輸出)
-
localhost:1337
=> "default page." -
localhost:1337/index
=> "I am index." -
localhost:1337/test
=> "this is test page." -
localhost:1337/xxs21a
=> "default page"
References
Node入門
Node.js 基礎 Node.js 中文電子書