var http = require("http");//獲取http對象 var url = require("url");//獲取url對象 //http、url都是系統自帶的模塊,而下面的requestHandlers是咱們手動編寫的模塊,對應當前目錄下的requestHandlers.js文件 var requestHandlers = require("./requestHandlers"); //onRequest函數,用於處理http請求,不一樣的url請求交由不一樣的函數進行處理 function onRequest(request, response){ var pathname = url.parse(request.url).pathname;//獲取請求的URL //requestHandlers的handle屬性又是一個對象,該對象包含多組屬性:屬性值,屬性名對應uri,屬性值對應處理函數,詳見requestHandlers.js if(typeof requestHandlers.handle[pathname] === "function") requestHandlers.handle[pathname](request, response); else { console.log("No request handler found for " + pathname); response.writeHead(404, {"Content-Type": "text/html;charset=utf-8"}); response.write("您訪問的頁面不存在!訪問<a href='/'>首頁</a>"); response.end(); } } var server = http.createServer(onRequest);//函數onRequest做爲createServer的參數,這樣瀏覽器每發送一次請求,服務器中該函數都會被調用一次 server.listen(8888); //上面兩句能夠合寫成http.createServer(onRequest).listen(8888);
var handle = {}; var formidable = require("formidable"); handle["/"] = start; handle["/start"] = start; handle["/upload"] = upload; function start(request, response) { var body = '<html>'+ '<head>'+ '<meta http-equiv="Content-Type" content="text/html; '+ 'charset=UTF-8" />'+ '</head>'+ '<body>'+ '<form action="/upload" method="post">'+ '學號:<input type="text" name="id" /><br /><br />'+ '姓名:<input type="text" name="name" /><br /><br />'+ '<input type="submit" value="提交" />'+ '</form>'+ '</body>'+ '</html>'; response.writeHead(200, {"Content-Type": "text/html"}); response.write(body); response.end(); } function upload(request, response) { var form = new formidable.IncomingForm(); form.parse(request, function(error, fields, files) { console.log("id:" + fields.id); console.log("name:" + fields.name); response.writeHead(200, {"Content-Type": "text/html;charset=utf-8"}); response.write("id:" + fields.id + "<br>"); response.write("name:" + fields.name); response.end(); }); } exports.handle = handle; exports.start = start; exports.upload = upload;