我正在尝试与本地 postgres 数据库建立连接并使用express 来执行api 端点。我不确定为什么会收到此错误。
//db.js
const { Pool } = require("pg");
const pg = require("pg");
require("dotenv").config(); //get credentials
pg.defaults.ssl = true;
const connectionString = process.env.NODE_ENV === "production"
? process.env.DATABASE_URL
: `postgresql://${process.env.PG_USER}:${process.env.PG_PASS}@${process.env.PG_HOST}:${process.env.PG_PORT}/${process.env.PG_DATABASE}`;
const conn = new Pool({
connectionString: connectionString,
ssl: { rejectUnauthorized: false }
});
module.exports = conn;
//index.js
const express = require('express');
const app = express();
const pool = require("./db"); //stores super secret db info
const cors = require("cors");
const PORT = process.env.PORT || 5500;
app.use(cors());
app.use(express.json()); // => req.body
app.use(express.static('public'));
app.get("/apiv1/:tier", async (req, res) => {
try {
const { date, tier } = req.params;
const allData = await pool.query(
"SELECT * FROM previous WHERE tier=$1 ORDER BY DESC LIMIT 25;",
[tier]
);
const results = allData.rows;
console.log(results)
// const output = { "data": Object.fromEntries(
// results.map(
// item => [item.pokemon, item]
// ))
// };
// res.json(output);
} catch (error) {
console.log(error.message);
};
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}.`);
});
我的凭据有效,并且我的登陆页面已加载,但当我尝试转到
localhost:5500/apiv1/anything
时,我在控制台中收到错误页面和消息 The server does not support SSL connections
,但我已采取步骤允许 SSL 连接。
您的本地 postgreSQL 服务器似乎未启用 ssl。
在
db.js
中删除 ssl 选项,它应该可以工作:
const conn = new Pool({
connectionString: connectionString,
// ssl: { rejectUnauthorized: false } // remove this line
});
在你的 postgres uri 中使用
sslmode=disable
postgresql://user:pwd@localhost:5432/db?schema=public&sslmode=disable