Node.js -类型错误:客户端不是构造函数

xytpbqjk  于 2022-11-22  发布在  Node.js
关注(0)|答案(3)|浏览(166)

我正在尝试以下操作:

const { Client } = require('pg');

  console.log(Client);

  const client = new Client({
      user: 'Username censored',
      host: 'Host censored',
      database: 'gisuebung',
      password: 'Passworded censored',
      port: 5432,
  });
  
  client.connect();

但是,当我运行此程序时,我收到以下错误:Error in v-on handler: "TypeError: Client is not a constructor"
我在网上找到一个片段后写了这篇文章,似乎无论我在哪里看,人们都做了完全相同的事情。有人能告诉我我做错了什么吗?

chhkpiq4

chhkpiq41#

这是一个JS错误:
试试这个,它对我很有效:
const { Client } = require('pg');
const Client = require('pg').Client;
-- ES模块:
import pg from 'pg';
const Client = pg.Client;

anauzrmj

anauzrmj2#

您的代码对于CommonJS是正确的。但是对于ESM,将引发此错误。
在ESM中运行的正确方法:

import pg from 'pg'

const client = new pg.Client(config.dbConfig)
wribegjk

wribegjk3#

试试这个,它对我很有效:

const { Client } = require('pg');
const client = new Client({
 user: "postgres",
 database: "databasename",
 port: 5432,
 host: "localhost",
 password: "yourpassword",
 ssl: false
});

client.connect();
client.query("select * from cad_client")
     .then(results => {
         const result = results.rows
         console.log(result)
     })
     .finally(() => client.end())

相关问题