Node.js 的 http 模組提供了有用的函式和類別來建構 HTTP 伺服器。
HTTP 核心模組是 Node 網路通訊的重要模組。
你可以透過以下方式引入此模組:
const http = require('http');
這個模組提供了一些屬性、方法和類別。
屬性
http.METHODS
這個屬性列出了所有支援的 HTTP 方法:
> require('http').METHODS
[ 'ACL',
 'BIND',
 'CHECKOUT',
 'CONNECT',
 'COPY',
 'DELETE',
 'GET',
 'HEAD',
 'LINK',
 'LOCK',
 'M-SEARCH',
 'MERGE',
 'MKACTIVITY',
 'MKCALENDAR',
 'MKCOL',
 'MOVE',
 'NOTIFY',
 'OPTIONS',
 'PATCH',
 'POST',
 'PROPFIND',
 'PROPPATCH',
 'PURGE',
 'PUT',
 'REBIND',
 'REPORT',
 'SEARCH',
 'SUBSCRIBE',
 'TRACE',
 'UNBIND',
 'UNLINK',
 'UNLOCK',
 'UNSUBSCRIBE' ]
http.STATUS_CODES
這個屬性列出了所有 HTTP 狀態碼及其描述:
> require('http').STATUS_CODES
{ '100': 'Continue',
 '101': 'Switching Protocols',
 '102': 'Processing',
 '200': 'OK',
 '201': 'Created',
 '202': 'Accepted',
 '203': 'Non-Authoritative Information',
 '204': 'No Content',
 '205': 'Reset Content',
 '206': 'Partial Content',
 '207': 'Multi-Status',
 '208': 'Already Reported',
 '226': 'IM Used',
 '300': 'Multiple Choices',
 '301': 'Moved Permanently',
 '302': 'Found',
 '303': 'See Other',
 '304': 'Not Modified',
 '305': 'Use Proxy',
 '307': 'Temporary Redirect',
 '308': 'Permanent Redirect',
 '400': 'Bad Request',
 '401': 'Unauthorized',
 '402': 'Payment Required',
 '403': 'Forbidden',
 '404': 'Not Found',
 '405': 'Method Not Allowed',
 '406': 'Not Acceptable',
 '407': 'Proxy Authentication Required',
 '408': 'Request Timeout',
 '409': 'Conflict',
 '410': 'Gone',
 '411': 'Length Required',
 '412': 'Precondition Failed',
 '413': 'Payload Too Large',
 '414': 'URI Too Long',
 '415': 'Unsupported Media Type',
 '416': 'Range Not Satisfiable',
 '417': 'Expectation Failed',
 '418': 'I\'m a teapot',
 '421': 'Misdirected Request',
 '422': 'Unprocessable Entity',
 '423': 'Locked',
 '424': 'Failed Dependency',
 '425': 'Unordered Collection',
 '426': 'Upgrade Required',
 '428': 'Precondition Required',
 '429': 'Too Many Requests',
 '431': 'Request Header Fields Too Large',
 '451': 'Unavailable For Legal Reasons',
 '500': 'Internal Server Error',
 '501': 'Not Implemented',
 '502': 'Bad Gateway',
 '503': 'Service Unavailable',
 '504': 'Gateway Timeout',
 '505': 'HTTP Version Not Supported',
 '506': 'Variant Also Negotiates',
 '507': 'Insufficient Storage',
 '508': 'Loop Detected',
 '509': 'Bandwidth Limit Exceeded',
 '510': 'Not Extended',
 '511': 'Network Authentication Required' }
http.globalAgent
指向 http.Agent 類別的全域實例的物件。
http.Agent 類別負責管理和重複使用 HTTP 客戶端的連線,是 Node HTTP 網路的關鍵元件。
後續將更詳細介紹 http.Agent 類別。
方法
http.createServer()
回傳一個新的 http.Server 類別的實例。
使用方式如下:
const server = http.createServer((req, res) => {
 // 使用回呼函式處理每個請求
});
http.request()
對伺服器發起 HTTP 請求,並建立一個 http.ClientRequest 類別的實例。
http.get()
類似於 http.request(),但自動將 HTTP 方法設為 GET,並自動呼叫 req.end()。
類別
HTTP 模組提供了 5 個類別:
- http.Agent
- http.ClientRequest
- http.Server
- http.ServerResponse
- http.IncomingMessage
http.Agent
Node 建立了一個 http.Agent 類別的全域實例,負責管理和重複使用 HTTP 客戶端的連線,是 Node HTTP 網路的關鍵元件。
此物件確保每個發送至伺服器的請求都會排隊並重複使用單一個 Socket。
它同時維護著一個 Socket 池,對於效能來說非常重要。
http.ClientRequest
當執行 http.request() 或 http.get() 時,會建立一個 http.ClientRequest 物件。
在接收到回應時,會觸發 response 事件,並將 http.IncomingMessage 類別的實例作為參數傳入。
可透過以下兩種方式讀取回應的資料:
- 可以呼叫 response.read()方法
- 在 response事件的處理器中,可以設定一個data事件監聽器,以監聽串流進來的資料。
http.Server
透過 http.createServer() 建立新的伺服器時,常常會返回 http.Server 類別的實例。
一旦有伺服器物件,你就可以存取它的方法:
- close()停止伺服器接受新的連線
- listen()開啟 HTTP 伺服器並監聽連線
http.ServerResponse
http.Server 建立並作為 request 事件的第二個參數傳遞。
它在代碼中通常被稱為 res:
const server = http.createServer((req, res) => {
 // res 是一個 http.ServerResponse 物件
});
在處理程序中,你總會呼叫 end() 方法,它會關閉回應,訊息完成,伺服器可以將其發送到客戶端。每個回應都必須呼叫一次。
這些方法用於與 HTTP 標頭互動:
- getHeaderNames()取得已經設定的 HTTP 標頭名稱列表
- getHeaders()取得已經設定的 HTTP 標頭的副本
- setHeader('headername', value)設定 HTTP 標頭的值
- getHeader('headername')取得已經設定的 HTTP 標頭
- removeHeader('headername')移除已經設定的 HTTP 標頭
- hasHeader('headername')如果回應中有該標頭已經設定,則返回 true
- headersSent()如果標頭已經發送到客戶端,則返回 true
在處理標頭後,可以呼叫 response.writeHead() 來將標頭發送到客戶端,它接受 statusCode 作為第一個參數,可選的狀態訊息,以及標頭物件。
要將資料送到客戶端的回應主體,可以使用 write()。它會將緩衝的資料傳送到 HTTP 回應串流中。
如果尚未使用 response.writeHead() 發送標頭,它將首先發送標頭,其中包含請求中設定的狀態碼和訊息,你可以透過設定 statusCode 和 statusMessage 的值進行編輯:
response.statusCode = 500;
response.statusMessage = 'Internal Server Error';
http.IncomingMessage
當監聽 request 事件時,由 http.Server 建立 http.IncomingMessage 物件;當監聽 response 事件時,由 http.ClientRequest 建立。
它可用於存取回應的訊息:
- 狀態碼,使用其 statusCode和statusMessage方法
- 標頭,使用其 headers方法或rawHeaders
- HTTP 方法,使用其 method方法
- HTTP 版本,使用 httpVersion方法
- URL,使用 url方法
- 底層 socket,使用 socket方法
資料可透過串流存取,因為 http.IncomingMessage 實作了可讀串流介面。