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})
}
})
CodePudding user response:
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))
CodePudding user response:
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})
})