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

Node.js调用PostgreSQL数据库API异常:根路径报错,指定路径无响应

Node.js 连接PostgreSQL API 问题排查与修复

问题描述

通过Node.js编写API调用CentOS上的PostgreSQL数据库,目标是从sizing_results数据库的test_results表获取数据,但遇到以下问题:

  • 访问http://{SERVER IP}:3300/时返回“Cannot GET /”
  • 访问/test_results路径时请求无响应输出

代码问题分析

1. 根路径无路由处理

API仅定义了/test_results路由,未处理根路径/的请求,因此访问根路径会返回404错误。

2. 重复调用res.send()

在/test_results路由中连续调用两次res.send():

res.send('BLABLA')
res.send(result.rows);

HTTP响应只能发送一次,第一次调用后响应即结束,第二次调用不会执行,还会触发隐式错误。

3. 数据库连接关闭错误

client.end未加括号,仅为函数引用而非调用;且逻辑上在查询回调执行前就尝试关闭连接,会导致查询流程中断。

4. 未处理查询错误

数据库查询出错时,未给客户端返回任何响应,导致请求一直挂起、无输出。

修正后的代码

db_connection.js(保持不变)

const {Client} = require('pg')

const client = new Client({
  user: 'postgres',
  database: 'sizing_results',
  password: 'password',
  port: 5432,
  host: 'localhost',
})

module.exports = client

api.js(修正版)

const client = require('./db_connection.js')
const express = require('express');
const app = express();

// 处理根路径请求
app.get('/', (req, res) => {
    res.send('API 运行中,可访问 /test_results 获取数据');
});

app.get('/test_results', (req, res)=>{
    client.query(`select * from test_results`, (err, result)=>{
        if(err){
            // 返回错误信息
            res.status(500).send({ error: err.message });
            return;
        }
        // 仅发送一次响应
        res.send(result.rows);
        // 查询完成后关闭连接
        client.end();
    });
})

// 数据库连接成功后再启动服务
client.connect()
    .then(() => {
        app.listen(3300, ()=>{
            console.log("Server is now listening at port 3300");
        });
    })
    .catch(err => {
        console.error('数据库连接失败:', err);
    });

额外建议

生产环境建议使用连接池替代单个客户端连接,避免频繁创建/关闭连接的性能开销,修改db_connection.js如下:

const { Pool } = require('pg')

const pool = new Pool({
  user: 'postgres',
  database: 'sizing_results',
  password: 'password',
  port: 5432,
  host: 'localhost',
  max: 10, // 最大连接数
  idleTimeoutMillis: 30000, // 连接闲置超时时间
})

module.exports = pool

对应的api.js使用连接池查询,无需手动关闭连接:

const pool = require('./db_connection.js')
// ...
app.get('/test_results', (req, res)=>{
    pool.query(`select * from test_results`, (err, result)=>{
        if(err){
            res.status(500).send({ error: err.message });
            return;
        }
        res.send(result.rows);
    });
})
// ...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 07:15:30