標籤:nodejs路由模組使用
-
建立路由模組(route.js)
function route(pathname){
console.log("About to route a request for "+pathname);
}
exports.route = route;
建立http服務模組(server.js)var http = require("http");var url = require("url");function start(route){function onRequest(request,response){var pathname = url.parse(request.url).pathname;if (pathname != "/favicon.ico") {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來使用http伺服器模組和路由模組var http = require("./server");var router = require("./route");http.start(router.route);執行index.js並查看結果
執行命令:node index.js
訪問如下地址:http://localhost:8888/demo
執行結果:
Server has started
Request for /demo received
About to route a request for /demo
本文出自 “素顏” 部落格,請務必保留此出處http://suyanzhu.blog.51cto.com/8050189/1894049
nodejs路由模組使用