http模塊主要用於創建http server服務,並且
- 支持更多特性
- 不緩沖請求和響應
- 處理流相關
本文還用到url模塊和path模塊,還有fs模塊。url模塊用於解析url,path模塊用於處理和轉換文件路徑。
一、簡單應用
代碼如下:
// 文件名:demo.js // 引入http模塊 var http = require('http'); // 創建http server http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/');
$ node demo.js運行后,在瀏覽器可看到Hello World。
通過簡單的http.createServer()創建一個server,通過server.on綁定事件處理函數,通過server.listen監聽。 一個簡單的http服務器就完成了。
二、稍復雜應用
所以代碼放在app文件夾匯總,如下。

1、server.js
功能:創建http服務,監聽請求,讓route處理。
// // 創建http server // // 加載所需模塊 var http = require('http'); var url = require('url'); var fs = require('fs'); // 設置ip和端口 // 實際應用中,可以把這些寫到配置文件中 var host = '127.0.0.1', port = 8080; // 創建http server function start(route, handle) { // 參數 // route 判斷url是否存在,存在則調用handle處理,不存在則返回404 // handle 處理不同的url請求 // 處理request請求 function onRequest(req, res) { // 使用url.parse()方法解析url // 它會把url string轉化為一個object // 這樣我們就可以很方便的獲取url中的host、port、pathname等值了 var pathname = url.parse(req.url).pathname; console.log('Request for ' + pathname + ' received.'); // 判斷並處理不同url請求 // 后面介紹此方法 route(handle, pathname, res, req); } // 使用http.createSserver()方法創建http server // 並傳入onRequest()方法 // 然后使用listen()方法監聽指定地址 http.createServer(onRequest).listen(port, host); console.log('Server has started and listening on ' + host + ':' + port); } // 導出 start 方法 exports.start = start;
server.js中用到了http模塊、url模塊和fs模塊。
使用url.parse()方法解析url,把url string轉化為一個object,這樣我們就可以很方便的獲取url中的host,port,pathanme等值了。
var pathname = url.parse(request.url).pathname;
例:請求url:127.0.0.1:8088/about時req.url為:/about 。
最后導出start方法以便在主程序中使用。
2、router.js
功能: route判斷url是否存在,存在則調用handle處理,不存在則返回404。
var fs = require('fs'); // 路由函數 // 處理不同url的請求 // 並返回相應內容 function route(handle, pathname, res, req) { console.log('About to route a request for ' + pathname); // 判斷此url是否存在特定處理函數 // 存在則調用handle處理 // 不存在則返回404頁面 if (typeof handle[pathname] === 'function') { // 后面介紹handle函數 handle[pathname](res, req); } else { console.log('No request handler found for ' + pathname); // 讀取404頁面 // 所有頁面都存放在view文件夾下 var content = fs.readFileSync('./views/404.html'); res.writeHead(404, { 'Content-Type': 'text/html' }); res.write(content); res.end(); } } // 導出 route 方法 exports.route = route;
路由轉發,如果url存在(通過handle判斷的)交由handle處理,否則返回404頁面。
3、requestHandlers.js
功能:handle處理不同的url請求。
代碼如下:
// 處理url請求 var fs = require('fs'); // home.html 主頁 function home(res) { console.log('Request handler "home" was called.'); // 讀取home.html文件 var content = fs.readFileSync('./views/home.html'); res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(content); res.end(); } // about.html 關於頁面 function about(res) { console.log('Request handler "about" was called.'); // 讀取about.html文件 var content = fs.readFileSync('./views/about.html'); res.write(200, { 'Content-Type': 'text/html' }); res.write(content); res.end(); } // 導出頁面處理函數 exports.home = home; exports.about = about;
4、主程序main.js
上面是創建http server,判斷url,處理url。
現在寫主程序來運行http server,代碼如下:
// 主程序 // 引入server,router及requestHandler var server = require('./server'); var router = require('./router'); var requestHandlers = require('./requestHandlers'); // 保存url處理方法 var handle = {}; handle['/'] = requestHandlers.home; handle['/about'] = requestHandlers.about; // 啟動http server server.start(router.route, handle);
至此,所有服務器代碼寫完。
5、 用到的html文件
app文件夾的的views文件夾下,創建home.html,about.html和404.html如下。
home.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Home page</title> </head> <body> <p>home page</p> </body> </html>
about.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>About page</title> </head> <body> <p>about page</p> </body> </html>
404.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>404 page</title> </head> <body> <p>404 page not found</p> </body> </html>
6、運行程序
$ node main.js
訪問http://127.0.0.1:8080會看到home page頁面。
訪問http://127.0.0.1:8080/about顯示about page頁面。
其他顯示404 page 頁面。

三、排錯
錯誤1:
throw er; // Unhandled 'error' event

出現這種錯誤一般就是已經運行的另一個服務器使用了相同的端口,換一個端口就可以了。
本文作者starof,因知識本身在變化,作者也在不斷學習成長,文章內容也不定時更新,為避免誤導讀者,方便追根溯源,請諸位轉載注明出處:http://www.cnblogs.com/starof/p/5038890.html有問題歡迎與我討論,共同進步。
