我的Node.js应用程序可以通过npm pg模块与本地的Postgres数据库配合使用。 我也可以通过命令行使用heroku pg:psql命令连接到托管在Heroku上的Postgres数据库(免费的Hobby Dev计划)。 但是,当我的Node.js应用程序尝试查询托管在Heroku上的Postgres数据库时,我会收到一个“自签名证书”错误。
以下是带有“自签名证书”错误的输出内容:
(node:2100) UnhandledPromiseRejectionWarning: Error: self signed certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1051:34)
at TLSSocket.emit (events.js:189:13)
at TLSSocket._finishInit (_tls_wrap.js:633:8)
(node:2100) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:2100) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
D:\MY\DEV\PROJECTS\AdsSubscribeBot\test.js:57
if (err) throw err;
^
Error: Connection terminated unexpectedly
at Connection.con.once (D:\MY\DEV\PROJECTS\AdsSubscribeBot\node_modules\pg\lib\client.js:264:9)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:189:13)
at Socket.<anonymous> (D:\MY\DEV\PROJECTS\AdsSubscribeBot\node_modules\pg\lib\connection.js:76:10)
at Socket.emit (events.js:194:15)
at TCP._handle.close (net.js:597:12)
重现此错误的最简单方式是尝试使用Heroku开发中心中提供的Node.js示例代码进行连接:
https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js以下是引起self signed certificate
错误的代码示例:
const connectionString = 'postgres://USERNAME:PASSWORD@HOST:PORT/DB_NAME';
const { Client } = require('pg');
const client = new Client({
connectionString: connectionString,
ssl: true
});
client.connect();
client.query('SELECT * FROM users;', (err, res) => {
if (err) throw err;
for (let row of res.rows) {
console.log(JSON.stringify(row));
}
client.end();
});
也许有人曾经遇到过相同的问题并知道如何解决它。提前感谢任何帮助。