nodejs入門--簡單的請求處理案例


首先,讓請求處理程序返回需要在瀏覽器中顯示的信息開始,在項目根目錄中建立requestHandler.js,並寫入以下內容:

function start(){
console.log("Reaquest handler 'start' was called.");
return "Hello Start";
}

function upload(){
console.log("Request handler 'upload' was called.");
return "Hellow
Upload";
}

exports.start=start;
exports.upload=upload;

請求路由需要將請求處理程序返回給他的信息返回給服務器,因此,我們需要新建一個router.js,並增加以下內容:
function route(handle,pathname) {
console.log("About to route a requeset 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;

正如上述代碼所示,當請求無法路由的時候,我們也返回了一些相關的錯誤信息。最后,我們需要建立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;
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;
最后,建立我們的index.js,並運行
var server = require("./server");
var router = require("./route");
var requestHandles = require("./requestHandlers");

var handle = {};
handle["/"]=requestHandles.start;
handle["/start"]=requestHandles.start;
handle["/upload"]=requestHandles.upload;

server.start(router.route,handle);


當我們請求http://localhost:8888/start,瀏覽器會輸出“hello start”,當輸入http://localhost:8888/upload,瀏覽器會輸出“hello Upload”,
當請求http://localhost:8888/end,會顯示“404 Not found”,一個簡單的請求處理的nodejs案例就實現了。
 



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM