1.处理请求模块(requestHandlers.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;
2.路由模块(route.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;
3.服务器模块(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;
if (pathname != "/favicon.ico") {
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;
4.调用相应模块(index.js)
var server = require("./server");
var router = require("./route");
var requestHandlers = require("./requestHandlers");
var handle = {};
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route,handle);
5.执行index.js
node index.js
访问:http://localhost:8888/start
输出结果:
Hello start
访问:http://localhost:8888/upload
输出结果:
Hello Upload
访问:http://localhost:8888/other
输出结果:
404 Not found