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

恭喜,第一個HTTP服務器運行並響應所有的HTTP請求在端口8081。