Node.js v18.18.2 文档


目录

HTTPS#

稳定性:2 - 稳定

源代码: 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#

HTTPS 的Agent对象类似于http.Agent。请参阅 https.request()了解更多信息。

new Agent([options])#

  • options <Object>要在代理上设置的可配置选项集。可以具有与http.Agent(options)相同的字段,并且
    • maxCachedSessions <number> TLS 缓存会话的最大数量。使用0禁用 TLS 会话缓存。默认值: 100

    • servername <string>要发送到服务器的服务器名称指示扩展的值 。使用空字符串''禁用发送扩展。 默认值:目标服务器的主机名,除非使用 IP 地址指定目标服务器,在这种情况下,默认值为''(无扩展名)。

      有关 TLS 会话重用的信息,请参阅Session Resumption

事件:'keylog'#
  • line <Buffer> ASCII 文本行,采用 NSS SSLKEYLOGFILE格式。
  • 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#

请参阅http.Server了解更多信息。

server.close([callback])#

请参阅node:http模块中的server.close()

server.closeAllConnections()#

请参阅node:http 模块中的server.closeAllConnections()

server.closeIdleConnections()#

请参阅node:http 模块中的server.closeIdleConnections()

server.headersTimeout#

请参阅node:http 模块中的server.headersTimeout

server.listen()#

启动 HTTPS 服务器侦听加密连接。此方法与net.Server中的 server.listen()相同。

server.maxHeadersCount#

请参阅node:http 模块中的server.maxHeadersCount

server.requestTimeout#

请参阅node:http模块中的 server.requestTimeout

server.setTimeout([msecs][, callback])#

请参阅node:http 模块中的server.setTimeout()

server.timeout#

请参阅node:http 模块中的server.timeout

server.keepAliveTimeout#

请参阅node:http 模块中的server.keepAliveTimeout

https.createServer([options][, requestListener])#

// 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])#

类似于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])#

向安全 Web 服务器发出请求。

还接受 来自tls.connect()的以下附加optionscacertciphersclientCertEnginecrldhparamecdhCurvehonorCipherOrderkeypassphrasepfxrejectUnauthorizedsecureOptionssecureProtocolservernamesessionIdContexthighWaterMark

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:[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 

NodeJS中文文档为Read dev Docs平台提供托管,中文NodeJS文档均由英文版NodeJS文档翻译,版权属于nodejs.org