0

I have tried a simple query to my Postgresql database, with Express and pg, but my query blocks the server before the console.log

It starts with : node app.js

Here is extract of the code of app.js

var router = express.Router()
const { Client } = require('pg')

const client = new Client({
    user: 'dev', 
    host: 'localhost',
    database: 'fransua',
    password: 'azerty123456789',
    port: 5432
})

client.connect()

router.get('/database', async (req, res) => {
    client.query("SELECT * FROM employees WHERE first_name= $1", ['Roam']), (err,res) => {
        console.log(err ? err.stack : res.rows)
        res.render("database", {title: "Database", posts: posts})
    }
})

2 Answers 2

1

Try it like this:

Create a query statement:

const query = {
   // give the query a unique name
   name: 'fetch-employee',
   text: 'SELECT * FROM employees WHERE first_name= $1',
   values: ['Roam'],
  }

Than run the operation with a promise:

// promise
 client
  .query(query)
  .then(res => console.log(res.rows[0]))
  .catch(e => console.error(e.stack))
Sign up to request clarification or add additional context in comments.

Comments

1

You made a typo. Delete the closing parenthesis after ['Roam'] and insert one after the closing brace:

client.query("SELECT * FROM employees WHERE first_name= $1", ['Roam'], (err,res) => {
  console.log(err ? err.stack : res.rows)
  res.render("database", {title: "Database", posts: posts})
})

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.