VSCode执行npm run dev启动站点遇TypeError错误,求解决
解决启动Node.js项目时pg模块抛出的TypeError(key参数为null)
错误信息:
TypeError: The "key" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, DataView, KeyObject, or CryptoKey. Received null at new NodeError (node:internal/errors:372:5) at prepareSecretKey (node:internal/crypto/keys:580:11) at new Hmac (node:internal/crypto/hash:132:9) at Object.createHmac (node:crypto:162:10) at hmacSha256 (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg\lib\sasl.js:191:17) at Hi (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg\lib\sasl.js:195:13) at Object.continueSession (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg\lib\sasl.js:40:24) at Client._handleAuthSASLContinue (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg\lib\client.js:257:10) at Connection.emit (node:events:527:28) at Connection.emit (node:domain:475:12) [nodemon] app crashed - waiting for file changes before starting...
问题原因
报错栈指向pg模块的SASL认证流程,说明PostgreSQL客户端在生成HMAC签名时,传入的密钥参数为null——核心原因是数据库连接配置中的密码字段未正确设置(为空或未定义)。
解决方案
检查数据库连接配置:找到项目中配置PostgreSQL连接的文件(如config.js、数据库初始化代码或.env环境文件),确认
password字段为有效字符串,不存在null/undefined的情况。
示例配置(pg.Client对象):const { Client } = require('pg'); const client = new Client({ user: 'your_db_username', host: 'localhost', database: 'your_db_name', password: 'your_valid_db_password', // 必须设置为数据库的真实密码 port: 5432, });若使用连接字符串,确保格式正确:
postgresql://username:password@host:port/database校验环境变量读取:如果用.env文件管理配置,检查文件中
DB_PASSWORD(或对应变量名)是否正确赋值,且代码中读取变量时无拼写错误(比如误写为DB_PWD)。重新安装依赖:删除
node_modules和package-lock.json,执行npm install,确保pg模块版本与当前Node.js版本兼容(Node.js版本过高/过低可能引发加密参数兼容问题)。检查PostgreSQL认证规则:若配置无误仍报错,可查看PostgreSQL服务器的
pg_hba.conf文件,确认认证方式(如scram-sha-256)与pg模块版本匹配,或临时切换为md5认证测试是否解决问题。
内容的提问来源于stack exchange,提问作者Game And Mert
相关产品推荐
相关产品推荐

