Hello World HTTP 伺服器

首先,為你的平臺安裝 Node.js.

在這個例子中,我們將建立一個偵聽埠 1337 的 HTTP 伺服器,它將 Hello, World! 傳送到瀏覽器。請注意,你可以使用當前未被任何其他服務使用的任何你選擇的埠號,而不是使用埠 1337。

http 模組是 Node.js 核心模組 (Node.js 源中包含的模組,不需要安裝其他資源)。http 模組提供使用 http.createServer() 方法建立 HTTP 伺服器的功能。要建立應用程式,請建立包含以下 JavaScript 程式碼的檔案。

const http = require('http'); // Loads the http module

http.createServer((request, response) => {

    // 1. Tell the browser everything is OK (Status code 200), and the data is in plain text
    response.writeHead(200, {
        'Content-Type': 'text/plain'
    });

    // 2. Write the announced text to the body of the page
    response.write('Hello, World!\n');

    // 3. Tell the server that all of the response headers and body have been sent
    response.end();

}).listen(1337); // 4. Tells the server what port to be on

使用任何檔名儲存檔案。在這種情況下,如果我們將其命名為 hello.js,我們可以通過轉到檔案所在的目錄並使用以下命令來執行應用程式:

node hello.js

然後可以使用 URL http:// localhost:1337http://127.0.0.1:1337 在瀏覽器中訪問建立的伺服器。

將出現一個簡單的網頁,頂部顯示 Hello World! 文字,如下面的螢幕截圖所示。

StackOverflow 文件

可編輯的線上示例。