- assert断言
- async_hooks异步钩子
- async_hooks/context异步上下文
- buffer缓冲区
- C++插件
- C/C++插件(使用Node-API)
- C++嵌入器
- child_process子进程
- cluster集群
- CLI命令行
- console控制台
- Corepack核心包
- crypto加密
- crypto/webcrypto网络加密
- debugger调试器
- deprecation弃用
- dgram数据报
- diagnostics_channel诊断通道
- dns域名服务器
- domain域
- Error错误
- events事件触发器
- fs文件系统
- global全局变量
- http超文本传输协议
- http2超文本传输协议2.0
- https安全超文本传输协议
- inspector检查器
- Intl国际化
- module模块
- module/cjsCommonJS模块
- module/esmECMAScript模块
- module/package包模块
- net网络
- os操作系统
- path路径
- perf_hooks性能钩子
- permission权限
- policy安全策略
- process进程
- punycode域名代码
- querystring查询字符串
- readline逐行读取
- repl交互式解释器
- report诊断报告
- stream流
- stream/web网络流
- string_decoder字符串解码器
- test测试
- timers定时器
- tls安全传输层
- trace_events跟踪事件
- tty终端
- url网址
- util实用工具
- v8引擎
- vm虚拟机
- wasi网络汇编系统接口
- worker_threads工作线程
- zlib压缩
Node.js v18.15.0 文档
- Node.js 18.15.0
- ► 目录
-
►
索引
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS模块
- module/esm ECMAScript模块
- module/package 包模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- policy 安全策略
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
- ► 其他版本
- 文档搜索
目录
https 安全超文本传输协议#
源代码: lib/https.js
HTTPS 是基于 TLS/SSL 的 HTTP 协议。 在 Node.js 中,作为单独的模块实现。
确定加密支持是否不可用#
可以在不支持 node:crypto 模块的情况下构建 Node.js。
在这种情况下,尝试 import https 或调用 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 类#
HTTPS 的 Agent 对象,类似于 http.Agent。
有关详细信息,请参阅 https.request()。
new Agent([options])#
options<Object> 要在代理上设置的可配置选项集。 可以具有与http.Agent(options)相同的字段,以及
'keylog' 事件#
line<Buffer> ASCII 文本行,采用 NSSSSLKEYLOGFILE格式。tlsSocket<tls.TLSSocket> 生成它的tls.TLSSocket实例。
当此代理管理的连接生成或接收密钥材料时(通常在握手完成之前,但不一定),则会触发 keylog 事件。
该密钥材料可以存储用于调试,因为它允许对捕获的 TLS 流量进行解密。
它可以为每个套接字多次触发。
一个典型的用例是将接收到的行附加到公共文本文件中,稍后软件(例如 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.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://localhost: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,但method始终设置为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默认值:443agent默认值:https.globalAgent
callback<Function>- 返回: <http.ClientRequest>
发出请求到安全的 Web 服务器。
还接受来自 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() 中的选项的示例:
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:xyz@example.com');
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) {
// 确保证书颁发给连接的主机
const err = tls.checkServerIdentity(host, cert);
if (err) {
return err;
}
// 固定公钥,类似于 HPKP pin-sha256 固定
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);
}
// 固定确切的证书,而不是公钥
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);
}
// 此循环仅供参考。
// 打印链中所有证书的证书和公钥指纹。
// 通常,在公共互联网上固定发行者的公钥,在敏感环境中固定服务的公钥。
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);
// 打印 HPKP 值
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