3

I am trying the following:

  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();
  

When I run this however, I get the following Error: Error in v-on handler: "TypeError: Client is not a constructor"

I wrote this after a snippet I found online and it seems everywhere I look people did the exact same thing. Can anyone tell me what I am doing wrong?

5
  • Not enough informaiton. It can be a number of different things though, the likeliest would be a version issue i.e., pg dependency. Look into the version your using, as this seems to be a common issue version 2.0 ~ Commented Oct 23, 2020 at 17:03
  • 1
    It worked well for me so try to check your dependencies or change your const name from client to something like pgClient to check if is not an issue with the destructuring Commented Oct 23, 2020 at 17:11
  • worked for me too! Commented Oct 23, 2020 at 17:35
  • What does "v-on handler" refer to? Commented Oct 23, 2020 at 18:42
  • I am working with Vue.js, so v-on handler comes from there Commented Oct 23, 2020 at 19:56

3 Answers 3

12

This is a JS error:

Try this, it worked for me:

const { Client } = require('pg'); 
// or
const Client = require('pg').Client;

-- ES module:

import pg from 'pg';
const Client = pg.Client;
Sign up to request clarification or add additional context in comments.

2 Comments

The missing piece here is the ESM part.
These aren't equivalent, the first sets Client twice.
1

Your code fine for CommonJS. But for ESM this error will raise.

Correct way to run in ESM:

import pg from 'pg'

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

Comments

-1

Try this, it worked for me:

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.