Search code examples
node.jspostgresqlexpressheroku-postgres

NodeJS+express Insert data into table multiple times


I'm new to nodeJs.

I'm trying to make a simple server(nodeJS + Postgres) that inserts a new row to the DB(based on the URL) every time the URL is called with parameters. The problem is, the following code works the first time the URL is called but the second time and on it doesn't insert the data in the DB.

How could I make it work every time the URL is called?

Thanks

const express = require('express')
const app = express()
const port = process.env.PORT || 3000
const { Client } = require('pg');

const client = new Client({
    connectionString: 'postgres://...........',
    ssl: true,
});



app.get('/item/', (req, res) =>
    (client.connect()
        .then(()=>console.log('sucessful connection to DB'))
        .then(()=>client.query(`INSERT INTO items(id,user) values('${req.query.id}','${req.query.user}')`))
        .then(res.send("user sent"))
        .catch(e=>console.log(e))
        .finally(()=>client.end())))



app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Solution

  • You're reusing the client, and you can't do that. It's better in your case to use a connection pool.

    const pool = new Pool({
       connectionString: 'postgres://...........',
       ssl: true,
    })
    
    app.get('/item/', (req, res, next) => {
    
         pool.query('...')
            .then(result => res.send('ok'))
            .catch(next)
    })
    

    Also, don't concatenate the values, otherwise you're open to SQL injections attacks. Use parameterized query instead