Created With

linkNode.js HTTP

參考資料:

[學習之路] Node.js 入門教學

Node.js Tutorial

How to build a REST API with TypeScript using only native modules

HTTP | Node.js v19.8.1 documentation


Node.js 的 HTTP 模組提供許多網站伺服器、資料傳遞相關的功能。

link常用功能

link引用 Node.js 的 http 模組

1linkconst http = require('http');

link建立伺服器

1linkconst server = http.createServer((request, response) => {

2link// 用 http 模組的 createServer 方法建立伺服器,處理 request 請求、response 回應

3link});

在上述函式中可使用 request 和 response 相關的功能,例如:

1link response.statusCode = 200;

2link // 設定回應的狀態代號為 200 (成功)

3link response.setHeader('Content-Type', 'text/plain');

4link // 設定標頭的內容類型,text/plain 是普通文字

5link

6link // 也可寫成

7link response.writeHead(200, { 'Content-Type': 'text/plain' });

1link response.write('Hello World\n');

2link // 設定回應內容

3link response.end();

4link // 送出回應

5link

6link // 也可寫成

7link response.end('Hello World\n');

link啟動伺服器

1linkconst hostname = '127.0.0.1', port = 3000;

2link// 設定網站主機名稱與通訊埠

3link

4linkserver.listen(port, hostname, () => {

5link// 開始 HTTP 伺服器的連線監聽

6link console.log(`Server running at http://${hostname}:${port}/`);

7link // 在終端機顯示訊息,說明目前在用的主機名稱和通訊埠

8link});

link範例

最常見的 Node.js 入門範例就是網站伺服器:

1linkconst http = require('http');

2link

3linkconst hostname = '127.0.0.1', port = 3000;

4link

5linkconst server = http.createServer((request, response) => {

6link response.writeHead(200, { 'Content-Type': 'text/plain' });

7link response.end('Hello World\n');

8link});

9link

10linkserver.listen(port, hostname, () => {

11link console.log(`Server running at http://${hostname}:${port}/`);

12link});

link執行

先把上述程式碼存在 server.js 檔案中,再打開任意終端機執行 node server.js 指令

執行後終端機應該會出現 Server running at http://127.0.0.1:3000/

在瀏覽器中開啟此網址會出現 Hello World

Node.js HTTP常用功能引用 Node.js 的 http 模組建立伺服器啟動伺服器範例執行

技術筆記

準備chevron_right
HTMLchevron_right
CSS 基礎chevron_right
JS 基礎chevron_right
Git & GitHubchevron_right
CSS 進階chevron_right
Node.jschevron_right

返回個人網站