Node.js入門範例程式


在使用Node.js建立實際“Hello, World!”應用程式之前,讓我們看看Node.js的應用程式的部分。Node.js應用程式由以下三個重要組成部分:

  1. 匯入需要模組: 我們使用require指令載入Node.js模組。

  2. 建立伺服器: 伺服器將監聽類似Apache HTTP Server用戶端的請求。

  3. 讀取請求,並返回響應: 在前面的步驟中建立的伺服器將讀取用戶端發出的HTTP請求,它可以從一個瀏覽器或控制台並返回響應。

建立Node.js應用

步驟 1 - 匯入所需的模組

我們使用require指令來載入HTTP模組和儲存返回HTTP,例如HTTP變數,如下所示:

var http = require("http");

步驟 2: 建立服務

在接下來的步驟中,我們使用HTTP建立範例,並呼叫http.createServer()方法來建立伺服器範例,然後使用伺服器範例監聽相關聯的方法,把它繫結在埠8081。 通過它使用引數的請求和響應函式。編寫範例實現返回 "Hello World".

http.createServer(function (request, response) {

   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

上面的程式碼建立監聽即HTTP伺服器。在本地計算機上的8081埠等到請求。

步驟 3: 測試請求和響應

讓我們把步驟1和2寫到一個名為main.js的檔案,並開始啟動HTTP伺服器,如下所示:

var http = require("http");

http.createServer(function (request, response) {

   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

現在執行main.js來啟動伺服器,如下:

$ node main.js

驗證輸出。伺服器已經啟動

Server running at http://127.0.0.1:8081/

發出Node.js伺服器的一個請求

在任何瀏覽器中開啟地址:http://127.0.0.1:8081/,看看下面的結果。

First Application

恭喜,第一個HTTP伺服器執行並響應所有的HTTP請求在埠8081。