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

使用postgres库实现CRUD遇TypeError: sql不是函数,请求帮助

解决TypeError: sql is not a function(postgres库+Express场景)

问题根源

你遇到的TypeError: sql is not a function,核心原因是从./controller/postgres_connection.js导入的sql并非postgres库生成的可调用查询实例。postgres库的核心逻辑是先初始化数据库连接得到一个函数实例,才能通过模板字符串语法执行SQL语句。

解决步骤

1. 修正postgres_connection.js的导出逻辑

确保你的postgres_connection.js正确初始化postgres连接并导出可调用的实例:

const postgres = require('postgres');

// 替换为你的PostgreSQL实际连接配置
const sql = postgres({
  host: 'localhost', // 数据库地址
  port: 5432, // 默认端口
  database: 'your_database_name', // 目标数据库名
  user: 'your_db_username', // 数据库用户名
  password: 'your_db_password', // 数据库密码
});

module.exports = sql;

如果之前这个文件未正确导出初始化后的sql函数(比如导出了原始postgres模块、空对象等),就会导致调用sql时报错。

2. 修正getUserDetails的参数传递逻辑

你调用getUserDetails(userID, password)时传入了两个独立参数,但函数定义使用了解构语法{ userID, password },这会导致参数解构失败,最终userID和password值为undefined。二选一修改即可:

方式一:修改函数定义为普通参数

async function getUserDetails(userID, password) {
  try {    
    const users = await sql`
      insert into application_form
      (uid, password)
      values
      (${userID}, ${password})
      returning uid, password
    `;
    return users;
  } catch(error) {
    console.log(error);
    // 可选:添加错误抛出或返回逻辑,比如 throw error;
  }
}

方式二:调用时传入对象

await console.log(getUserDetails({ userID, password }));

3. 清理无效代码

删除catch块内无意义的your text模板字符串,避免代码冗余。

验证

修改完成后重启Express服务,访问/user/insert接口,即可正常执行插入操作并在日志中看到返回的用户数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:57:23