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
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。