您好,登錄后才能下訂單哦!
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.調(diào)用相應模塊(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.執(zhí)行index.js
node index.js
訪問:http://localhost:8888/start
輸出結(jié)果:
Hello start
訪問:http://localhost:8888/upload
輸出結(jié)果:
Hello Upload
訪問:http://localhost:8888/other
輸出結(jié)果:
404 Not found
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。