Node.js v21.7.2 文件
- Node.js v21.7.2
- ► 目錄
-
► 索引
- 斷言測試
- 非同步內容追蹤
- 非同步掛鉤
- 緩衝區
- C++ 附加元件
- 使用 Node-API 的 C/C++ 附加元件
- C++ 嵌入式 API
- 子程序
- 叢集
- 命令列選項
- 主控台
- Corepack
- 加密
- 偵錯器
- 已棄用的 API
- 診斷頻道
- DNS
- 網域
- 錯誤
- 事件
- 檔案系統
- 全域變數
- HTTP
- HTTP/2
- HTTPS
- 檢查器
- 國際化
- 模組:CommonJS 模組
- 模組:ECMAScript 模組
- 模組:
node:module
API - 模組:套件
- 網路
- 作業系統
- 路徑
- 效能掛鉤
- 權限
- 程序
- Punycode
- 查詢字串
- 讀取命令列
- REPL
- 報告
- 單一可執行檔應用程式
- 串流
- 字串解碼器
- 測試執行器
- 計時器
- TLS/SSL
- 追蹤事件
- TTY
- UDP/資料包
- URL
- 公用程式
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- 工作執行緒
- Zlib
- ► 其他版本
- ► 選項
HTTPS#
原始碼: lib/https.js
HTTPS 是透過 TLS/SSL 的 HTTP 協定。在 Node.js 中,它實作為一個獨立的模組。
判斷是否不支援加密#
Node.js 可以建立而不包含對 node:crypto
模組的支援。在這種情況下,嘗試從 https
import
或呼叫 require('node:https')
會導致擲回錯誤。
使用 CommonJS 時,可以使用 try/catch 捕捉擲回的錯誤
let https;
try {
https = require('node:https');
} catch (err) {
console.error('https support is disabled!');
}
使用字彙 ESM import
關鍵字時,只有在嘗試載入模組之前註冊 process.on('uncaughtException')
處理常式,才能捕捉錯誤(例如,使用預載入模組)。
使用 ESM 時,如果程式碼有可能在未啟用加密支援的 Node.js 版本上執行,請考慮使用 import()
函式,而不是詞彙 import
關鍵字
let https;
try {
https = await import('node:https');
} catch (err) {
console.error('https support is disabled!');
}
類別:https.Agent
#
類似於 http.Agent
的 HTTPS Agent
物件。請參閱 https.request()
以取得更多資訊。
new Agent([options])
#
options
<Object> 設定在代理程式上的可設定選項組。可以有與http.Agent(options)
相同的欄位,以及
事件:'keylog'
#
line
<Buffer> ASCII 文字行,格式為 NSSSSLKEYLOGFILE
。tlsSocket
<tls.TLSSocket> 產生此事件的tls.TLSSocket
執行個體。
當此代理程式管理的連線產生或收到金鑰資料時,就會發出 keylog
事件(通常在交握完成之前,但並非絕對)。此金鑰資料可儲存以進行除錯,因為它允許解密擷取的 TLS 流量。每個 socket 可能會發出多次事件。
常見的用例是將收到的行附加到共用文字檔,稍後再由軟體(例如 Wireshark)使用該檔案來解密流量
// ...
https.globalAgent.on('keylog', (line, tlsSocket) => {
fs.appendFileSync('/tmp/ssl-keys.log', line, { mode: 0o600 });
});
類別:https.Server
#
- 擴充:<tls.Server>
請參閱 http.Server
以取得更多資訊。
server.close([callback])
#
callback
<Function>- 傳回:<https.Server>
請參閱 node:http
模組中的 server.close()
。
server[Symbol.asyncDispose]()
#
呼叫 server.close()
並傳回一個 Promise,在伺服器關閉時完成。
server.closeAllConnections()
#
請參閱 node:http
模組中的 server.closeAllConnections()
。
server.closeIdleConnections()
#
請參閱 node:http
模組中的 server.closeIdleConnections()
。
server.headersTimeout
#
- <number> 預設值:
60000
請參閱 node:http
模組中的 server.headersTimeout
。
server.listen()
#
啟動 HTTPS 伺服器,以偵聽加密連線。此方法與 net.Server
中的 server.listen()
相同。
server.maxHeadersCount
#
- <number> 預設值:
2000
請參閱 node:http
模組中的 server.maxHeadersCount
。
server.requestTimeout
#
- <number> 預設值:
300000
請參閱 node:http
模組中的 server.requestTimeout
。
server.setTimeout([msecs][, callback])
#
msecs
<number> 預設值:120000
(2 分鐘)callback
<Function>- 傳回:<https.Server>
請參閱 node:http
模組中的 server.setTimeout()
。
server.timeout
#
- <number> 預設值:0(無逾時)
請參閱 node:http
模組中的 server.timeout
。
server.keepAliveTimeout
#
- <number> 預設值:
5000
(5 秒)
請參閱 node:http
模組中的 server.keepAliveTimeout
。
https.createServer([options][, requestListener])
#
options
<Object> 接受來自tls.createServer()
、tls.createSecureContext()
和http.createServer()
的options
。requestListener
<Function> 要新增至'request'
事件的監聽器。- 傳回:<https.Server>
// curl -k https://127.0.0.1:8000/
const https = require('node:https');
const fs = require('node:fs');
const options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
或
const https = require('node:https');
const fs = require('node:fs');
const options = {
pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
passphrase: 'sample',
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
https.get(options[, callback])
#
https.get(url[, options][, callback])
#
url
<string> | <URL>options
<Object> | <string> | <URL> 接受與https.request()
相同的options
,預設將方法設定為 GET。callback
<Function>
與 http.get()
相同,但適用於 HTTPS。
options
可以是物件、字串或 URL
物件。如果 options
是字串,則會自動使用 new URL()
進行剖析。如果它是 URL
物件,則會自動轉換為一般的 options
物件。
const https = require('node:https');
https.get('https://encrypted.google.com/', (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
}).on('error', (e) => {
console.error(e);
});
https.globalAgent
#
所有 HTTPS 要求的 https.Agent
全域執行個體。
https.request(options[, callback])
#
https.request(url[, options][, callback])
#
url
<string> | <URL>options
<Object> | <string> | <URL> 接受來自http.request()
的所有options
,預設值有些不同protocol
預設:'https:'
port
預設:443
agent
預設:https.globalAgent
callback
<Function>- 傳回:<http.ClientRequest>
對安全網頁伺服器提出要求。
也接受來自 tls.connect()
的下列額外 options
:ca
、cert
、ciphers
、clientCertEngine
、crl
、dhparam
、ecdhCurve
、honorCipherOrder
、key
、passphrase
、pfx
、rejectUnauthorized
、secureOptions
、secureProtocol
、servername
、sessionIdContext
、highWaterMark
。
options
可以是物件、字串或 URL
物件。如果 options
是字串,則會自動使用 new URL()
進行剖析。如果它是 URL
物件,則會自動轉換為一般的 options
物件。
https.request()
傳回 http.ClientRequest
類別的執行個體。ClientRequest
執行個體是可寫入串流。如果需要使用 POST 要求上傳檔案,請寫入 ClientRequest
物件。
const https = require('node:https');
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();
使用來自 tls.connect()
的 options
的範例
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
};
options.agent = new https.Agent(options);
const req = https.request(options, (res) => {
// ...
});
或者,透過不使用 Agent
來退出連線共用。
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
agent: false,
};
const req = https.request(options, (res) => {
// ...
});
使用 URL
作為 options
的範例
const options = new URL('https://abc:[email protected]');
const req = https.request(options, (res) => {
// ...
});
在憑證指紋或公開金鑰上釘選的範例(類似於 pin-sha256
)
const tls = require('node:tls');
const https = require('node:https');
const crypto = require('node:crypto');
function sha256(s) {
return crypto.createHash('sha256').update(s).digest('base64');
}
const options = {
hostname: 'github.com',
port: 443,
path: '/',
method: 'GET',
checkServerIdentity: function(host, cert) {
// Make sure the certificate is issued to the host we are connected to
const err = tls.checkServerIdentity(host, cert);
if (err) {
return err;
}
// Pin the public key, similar to HPKP pin-sha256 pinning
const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';
if (sha256(cert.pubkey) !== pubkey256) {
const msg = 'Certificate verification error: ' +
`The public key of '${cert.subject.CN}' ` +
'does not match our pinned fingerprint';
return new Error(msg);
}
// Pin the exact certificate, rather than the pub key
const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +
'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';
if (cert.fingerprint256 !== cert256) {
const msg = 'Certificate verification error: ' +
`The certificate of '${cert.subject.CN}' ` +
'does not match our pinned fingerprint';
return new Error(msg);
}
// This loop is informational only.
// Print the certificate and public key fingerprints of all certs in the
// chain. Its common to pin the public key of the issuer on the public
// internet, while pinning the public key of the service in sensitive
// environments.
do {
console.log('Subject Common Name:', cert.subject.CN);
console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256);
hash = crypto.createHash('sha256');
console.log(' Public key ping-sha256:', sha256(cert.pubkey));
lastprint256 = cert.fingerprint256;
cert = cert.issuerCertificate;
} while (cert.fingerprint256 !== lastprint256);
},
};
options.agent = new https.Agent(options);
const req = https.request(options, (res) => {
console.log('All OK. Server matched our pinned cert or public key');
console.log('statusCode:', res.statusCode);
// Print the HPKP values
console.log('headers:', res.headers['public-key-pins']);
res.on('data', (d) => {});
});
req.on('error', (e) => {
console.error(e.message);
});
req.end();
範例輸出
Subject Common Name: github.com
Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16
Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=
Subject Common Name: DigiCert SHA2 Extended Validation Server CA
Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A
Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=
Subject Common Name: DigiCert High Assurance EV Root CA
Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF
Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=
All OK. Server matched our pinned cert or public key
statusCode: 200
headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains