您还可以使用环境变量来设置连接。这是一个例子。
(假设您有一个 Postgres 数据库在端口 5432@localhost 上运行并且该数据库支持 SSL 连接)
.env
PGHOST=localhost
PGPORT=5432
PGDATABASE=mydb
PGUSER=pguser1
PGPASSWORD=mypassword
PGSSLMODE=require
(确保您设置PGSSLMODE
为require
如上所示。)
数据库.js
require('dotenv').config()
const { Pool } = require('pg')
// pools will use environment variables for connection information
const pool = new Pool()
// const pool = new Pool({ ssl: true }); This works too in the absence of PGSSLMODE
pool.on('error', function (err) {
console.log('idle client error', err.message, err.stack)
})
module.exports = {
pool,
query: (text, params, callback) => {
return pool.query(text, params, callback)
}
}
服务器.js
const express = require('express')
const { pool } = require('./db')
const app = express()
const port = 3000
app.get('/', async (req, res) => {
console.log('Request received...')
const result = await pool.query(`SELECT * FROM organization`);
res.send(result)
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
注意:如果您的 Postgres 数据库不支持 SSL 连接,当您的应用程序尝试进行查询时,您将遇到以下错误:
Error: The server does not support SSL connections
at Socket.<anonymous> (node_modules/pg/lib/connection.js:87:35)
参考: