用于PostgreSQL连接nodejs的SSL

Ste*_*fan 34 postgresql ssl node.js node-postgres

我正在尝试连接到我的Heroku PostgreSQL数据库,并且我一直收到SSL错误.有没有人知道如何在连接字符串中启用SSL?

postgres://user:pass@host:port/database;

一直在寻找它,但它似乎不是一个非常受欢迎的话题.顺便说一句,我正在运行Nodejs和node-pg模块及其connection-pooled方法:

pg.connect(connString, function(err, client, done) { /// Should work. });

评论非常感谢.

Jér*_*nge 59

你可以这样做:

postgres://user:pass@host:port/database?ssl=true
Run Code Online (Sandbox Code Playgroud)

  • 当我执行此操作时,我收到以下错误 - “服务器不支持 SSL 连接”。但是 ```psql "sslmode=require"``` 有效。因此,我倾向于认为正在使用的 ```"pg": "^4.3.0"``` npm 包有问题。有什么想法吗? (3认同)

fel*_*ekm 12

node-postgres创建新客户端时,您也可以使用以下代码:

var pg = require("pg");

var client = new pg.Client({
  user: "yourUser",
  password: "yourPass",
  database: "yourDatabase",
  port: 5432,
  host: "host.com",
  ssl: true
});

client.connect();

var query = client.query('CREATE TABLE people(id SERIAL PRIMARY KEY, name VARCHAR(100) not null)');

query.on('row', function(row) {
  console.log(row.name);
});

query.on('end', client.end.bind(client));
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 我采纳了您的建议并添加了“ssl: true”属性。事情就这么简单吗?我现在如何确保与数据库的连接确实安全? (3认同)

amo*_*tzg 11

对于 Google Cloud PG 和pg-promise,我也有类似的需求。我得到(使用?ssl=true)的错误是connection requires a valid client certificate.

SSL 连接没有记录在案,pg-promise但它建立在node-postgres 上。如链接中所述,ssl配置参数可以不仅仅是true

const pgp = require('pg-promise')();
const fs = require('fs');

const connectionConf = {
    host: 'myhost.com',
    port: 5432,
    database: 'specific_db_name',
    user: 'my_App_user',
    password: 'aSecretePass',
    ssl: {
        rejectUnauthorized : false,
        ca   : fs.readFileSync("server-ca.pem").toString(),
        key  : fs.readFileSync("client-key.pem").toString(),
        cert : fs.readFileSync("client-cert.pem").toString(),
  }

};
const new_db = pgp(connectionConf);
new_db.any('SELECT * FROM interesting_table_a LIMIT 10')
    .then(res => {console.log(res);})
    .catch(err => {console.error(err);})
    .then(() => {new_db.$pool.end()});
Run Code Online (Sandbox Code Playgroud)


Kar*_*ela 7

对于任何寻找 TypeORM 解决方案的人来说,它也是{ssl: true}.

完整示例:

const connectionOptions: PostgresConnectionOptions = {
    name: `default`,
    type: `postgres`,
    url: process.env.DATABASE_URL,
    ssl: process.env.DATABASE_SSL === `true`
}
Run Code Online (Sandbox Code Playgroud)