Latest web development tutorials

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 服務器架構(使用8081端口),創建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/plain
         response.writeHead(404, {'Content-Type': 'text/html'});
      }else{	         
         // HTTP 状态码: 200 : OK
         // Content Type: text/plain
         response.writeHead(200, {'Content-Type': 'text/html'});	
         
         // 响应文件内容
         response.write(data.toString());		
      }
      //  发送响应数据
      response.end();
   });   
}).listen(8081);

// 控制台会输出以下信息
console.log('Server running at http://127.0.0.1:8081/');

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

<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>

執行server.js 文件:

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

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

執行server.js 的控制台輸出信息如下:

Server running at http://127.0.0.1:8081/
Request for /index.htm received.     #  客户端请求信息

Gif 實例演示


使用Node 創建Web 客戶端

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

var http = require('http');

// 用于请求的选项
var options = {
   host: 'localhost',
   port: '8081',
   path: '/index.htm'  
};

// 处理响应的回调函数
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
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>

執行server.js 的控制台輸出信息如下:

Server running at http://127.0.0.1:8081/
Request for /index.htm received.   # 客户端请求信息

Gif 實例演示