tls.setDefaultCACertificates(certs)


设置 Node.js TLS 客户端使用的默认 CA 证书。如果提供的证书解析成功,它们将成为 tls.getCACertificates() 返回的默认 CA 证书列表,并由后续未指定自身 CA 证书的 TLS 连接使用。证书在设置为默认值之前将被去重。

¥Sets the default CA certificates used by Node.js TLS clients. If the provided certificates are parsed successfully, they will become the default CA certificate list returned by tls.getCACertificates() and used by subsequent TLS connections that don't specify their own CA certificates. The certificates will be deduplicated before being set as the default.

此函数仅影响当前的 Node.js 线程。HTTPS 代理缓存的先前会话不会受到此更改的影响,因此应在建立任何不需要的可缓存 TLS 连接之前调用此方法。

¥This function only affects the current Node.js thread. Previous sessions cached by the HTTPS agent won't be affected by this change, so this method should be called before any unwanted cachable TLS connections are made.

要使用系统 CA 证书作为默认证书:

¥To use system CA certificates as the default:

const tls = require('node:tls');
tls.setDefaultCACertificates(tls.getCACertificates('system'));import tls from 'node:tls';
tls.setDefaultCACertificates(tls.getCACertificates('system'));

此函数完全替换了默认的 CA 证书列表。要将其他证书添加到现有默认证书中,请获取当前证书并将其附加到它们:

¥This function completely replaces the default CA certificate list. To add additional certificates to the existing defaults, get the current certificates and append to them:

const tls = require('node:tls');
const currentCerts = tls.getCACertificates('default');
const additionalCerts = ['-----BEGIN CERTIFICATE-----\n...'];
tls.setDefaultCACertificates([...currentCerts, ...additionalCerts]);import tls from 'node:tls';
const currentCerts = tls.getCACertificates('default');
const additionalCerts = ['-----BEGIN CERTIFICATE-----\n...'];
tls.setDefaultCACertificates([...currentCerts, ...additionalCerts]);