Node.js Web 模組


什麼是 Web 伺服器?

Web伺服器一般指網站伺服器,是指駐留於因特網上某種類型電腦的程式,Web伺服器的基本功能就是提供Web資訊流覽服務。它只需支持HTTP協議、HTML文檔格式及URL,與客戶端的網路流覽器配合。

大多數 web 伺服器都支持服務端的腳本語言(php、python、ruby)等,並通過腳本語言從資料庫獲取數據,將結果返回給客戶端流覽器。

目前最主流的三個Web伺服器是Apache、Nginx、IIS。


Web 應用架構

  • Client - 客戶端,一般指流覽器,流覽器可以通過 HTTP 協議向伺服器請求數據。

  • Server - 服務端,一般指 Web 伺服器,可以接收客戶端請求,並向客戶端發送回應數據。

  • Business - 業務層, 通過 Web 伺服器處理應用程式,如與資料庫交互,邏輯運算,調用外部程式等。

  • Data - 數據層,一般由資料庫組成。


使用 Node 創建 Web 伺服器

Node.js 提供了 http 模組,http 模組主要用於搭建 HTTP 服務端和客戶端,使用 HTTP 伺服器或客戶端功能必須調用 http 模組,代碼如下:

var http = require('http');

以下是演示一個最基本的 HTTP 伺服器架構(使用 8080 端口),創建 server.js 檔,代碼如下所示:

實例

var http = require('http'); var fs = require('fs'); var url = require('url'); // 創建伺服器 http.createServer( function (request, response) { // 解析請求,包括檔案名 var pathname = url.parse(request.url).pathname; // 輸出請求的檔案名 console.log("Request for " + pathname + " received."); // 從檔系統中讀取請求的檔內容 fs.readFile(pathname.substr(1), function (err, data) { if (err) { console.log(err); // HTTP 狀態碼: 404 : NOT FOUND // Content Type: text/html response.writeHead(404, {'Content-Type': 'text/html'}); }else{ // HTTP 狀態碼: 200 : OK // Content Type: text/html response.writeHead(200, {'Content-Type': 'text/html'}); // 回應檔內容 response.write(data.toString()); } // 發送回應數據 response.end(); }); }).listen(8080); // 控制臺會輸出以下資訊 console.log('Server running at http://127.0.0.1:8080/');

接下來我們在該目錄下創建一個 index.html 檔,代碼如下:

index.html 檔

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>IT研修(xuhuhu.com)</title> </head> <body> <h1>我的第一個標題</h1> <p>我的第一個段落。</p> </body> </html>

執行 server.js 檔:

$ node server.js
Server running at http://127.0.0.1:8080/

接著我們在流覽器中打開地址:http://127.0.0.1:8080/index.html,顯示如下圖所示:

執行 server.js 的控制臺輸出資訊如下:

Server running at http://127.0.0.1:8080/
Request for /index.html received.     #  客戶端請求資訊


使用 Node 創建 Web 客戶端

Node 創建 Web 客戶端需要引入 http 模組,創建 client.js 檔,代碼如下所示:

實例

var http = require('http'); // 用於請求的選項 var options = { host: 'localhost', port: '8080', path: '/index.html' }; // 處理回應的回調函數 var callback = function(response){ // 不斷更新數據 var body = ''; response.on('data', function(data) { body += data; }); response.on('end', function() { // 數據接收完成 console.log(body); }); } // 向服務端發送請求 var req = http.request(options, callback); req.end();

新開一個終端,執行 client.js 檔,輸出結果如下:

$ node  client.js
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>IT研修(xuhuhu.com)</title>
</head>
<body>
    <h1>我的第一個標題</h1>
    <p>我的第一個段落。</p>
</body>
</html>

執行 server.js 的控制臺輸出資訊如下:

Server running at http://127.0.0.1:8080/
Request for /index.html received.   # 客戶端請求資訊