You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js连接PostgreSQL异常终止:接口请求报500错误求助

Node项目连接PostgreSQL时出现"Connection terminated unexpectedly"错误

我正在尝试将Node项目连接至PostgreSQL,项目服务已正常启动,在PostgreSQL中直接执行数据查询命令能返回正确结果,但调用项目仓库文件的get方法获取数据时失败,报错Connection terminated unexpectedly。

启动时正常控制台输出

Database user: postgres
Database host: xxx
Database name: Dependencies_Planner
Database password: xxx
Database port: 5432
Server is running on port 3000

请求接口时的错误信息

用Postman请求http://localhost:3000/api/requestor-names时,返回500 Internal Server Error,控制台输出:

controller
Entering getAllProductManagerNames method
Error executing query in getAllProductManagerNames: Error: Connection terminated unexpectedly
at C:\Users\USER\Desktop\DP\Dependencies-Planner-PRD\node_modules\pg-pool\index.js:45:11
at processTicksAndRejections (node:internal/process/task_queues:95:5)
Error fetching requestor names: Error: Connection terminated unexpectedly
at C:\Users\USER\Desktop\DP\Dependencies-Planner-PRD\node_modules\pg-pool\index.js:45:11
at processTicksAndRejections (node:internal/process/task_queues:95:5)

相关文件内容

.env文件

PGUSER="postgres"
PGHOST="xxx"
PGDATABASE="Dependencies_Planner"
PGPASSWORD="xxx"
PGPORT=5432
EXPRESS_PORT=3000
PGPASSWORD="***" # credentials removed

db配置文件

import { Pool } from 'pg';
import dotenv from 'dotenv';

dotenv.config();
console.log('Database user:', process.env.PGUSER);
console.log('Database host:', process.env.PGHOST);
console.log('Database name:', process.env.PGDATABASE);
console.log('Database password:', process.env.PGPASSWORD); 
console.log('Database port:', process.env.PGPORT);

const pool = new Pool({
  user: process.env.PGUSER,
  host: process.env.PGHOST,
  database: process.env.PGDATABASE,
 password: process.env.PGPASSWORD, 
  port: Number(process.env.PGPORT),
  
});

export default pool;

仓库文件(ProductManagerRepo)

import pool from '../config/db';

export default class ProductManagerRepo {
    static async getAllProductManagerNames(): Promise<{ name: string }[]> {
        try {
            console.log('Entering getAllProductManagerNames method');
            const result = await pool.query('SELECT name FROM productmanager');
            console.log('Query executed successfully, result:', result.rows);
            return result.rows;
        } catch (err) {
            console.error('Error executing query in getAllProductManagerNames:', err);
            throw err;
        }
    }
}

控制器文件

import { Request, Response } from 'express';
import ProductManagerRepo from '../repositories/productManagerRepo';

export const getRequestorNames = async (req: Request, res: Response): Promise<void> => {
    console.log('controller')
    try {
      const productManagerNames = await ProductManagerRepo.getAllProductManagerNames();
      res.json(productManagerNames);
    } catch (error) {
      console.error('Error fetching requestor names:', error);
      res.status(500).send('Internal Server Error');
    }
  };

Model文件

export interface ProductManager{
    email:string,
    name:string,
    groupId:number
    };

App主文件

import express from 'express';
import dotenv from 'dotenv';
import ProductmanagerRoutes from './src/routes/productManagerRoutes'

dotenv.config();

const app = express();
const port = process.env.EXPRESS_PORT || 3000;

app.use(express.json());

app.use('/api', ProductmanagerRoutes);

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

内容的提问来源于stack exchange,提问作者Rivky Friedman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 12:23:27