var http = require("http"); var url = require("url"); functionstart(route) { functiononRequest(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;
router.js
1 2 3 4 5
functionroute(pathname) { console.log("About to route a request for " + pathname); } exports.route = route;
執行
1 2
$ node index.js Server has started.
瀏覽localhost:888:
瀏覽結果如下:
1 2 3 4 5 6 7 8
Request for / received. About to route a request for /
// 以下是robots.txt和favicon.ico的Request Request for /robots.txt received. About to route a request for /robots.txt Request for /favicon.ico received. About to route a request for /favicon.ico
Request for /test received. About to route a request for /test Request queryString: abcd=1234&efgh=5678 Request queryString abcd value: 1234 Request queryString efgh value: 5678 Request for /favicon.ico received. About to route a request for /favicon.ico Request queryString: null Request queryString abcd value: undefined Request queryString edgh value: undefined