node-postgres 支持与你的 PostgreSQL 服务器建立 TLS/SSL 连接,只要服务器配置为支持它即可。在实例化池或客户端时,你可以在配置对象上提供 ssl
属性,它将传递给 节点 TLSSocket 的构造函数。
¥node-postgres supports TLS/SSL connections to your PostgreSQL server as long as the server is configured to support it. When instantiating a pool or a client you can provide an ssl
property on the config object and it will be passed to the constructor for the node TLSSocket.
自签名证书
¥Self-signed cert
这是一个可用于将客户端或池连接到 PostgreSQL 服务器的配置示例。
¥Here's an example of a configuration you can use to connect a client or a pool to a PostgreSQL server.
const config = {
database: 'database-name',
host: 'host-or-ip',
// this object will be passed to the TLSSocket constructor
ssl: {
rejectUnauthorized: false,
ca: fs.readFileSync('/path/to/server-certificates/root.crt').toString(),
key: fs.readFileSync('/path/to/client-key/postgresql.key').toString(),
cert: fs.readFileSync('/path/to/client-certificates/postgresql.crt').toString(),
},
}
import pg from 'pg'
const { Client, Pool } = pg
const client = new Client(config)
await client.connect()
console.log('connected')
await client.end()
const pool = new Pool(config)
const pooledClient = await pool.connect()
console.log('connected')
pooledClient.release()
await pool.end()
与 connectionString
一起使用
¥Usage with connectionString
如果你计划直接使用环境中的数据库连接字符串和配置对象中的 SSL 设置的组合,则必须避免在连接字符串中包含 sslcert
、sslkey
、sslrootcert
或 sslmode
中的任何一个。如果使用这些选项中的任何一个,则 ssl
对象将被替换,并且在那里提供的任何其他选项都将丢失。
¥If you plan to use a combination of a database connection string from the environment and SSL settings in the config object directly, then you must avoid including any of sslcert
, sslkey
, sslrootcert
, or sslmode
in the connection string. If any of these options are used then the ssl
object is replaced and any additional options provided there will be lost.
const config = {
connectionString: 'postgres://user:password@host:port/db?sslmode=require',
// Beware! The ssl object is overwritten when parsing the connectionString
ssl: {
rejectUnauthorized: false,
ca: fs.readFileSync('/path/to/server-certificates/root.crt').toString(),
},
}