skip to Main Content

I am using Typescript, Express, PostgresDB.

Here is my code for connecting to the database cluster.

import { Pool } from "pg";

const myPool = new Pool({
    host: `${process.env.DATABASE_URL}`,   //somedb.abc.us-east-1.rds.amazonaws.com
    database: `${process.env.DATABASE_NAME}`,   //dbName
    user: `${process.env.DATABASE_USER}`, //dbUser
    password: `${process.env.DATABASE_PASSWORD}`, //dbPassword
    port: 5432
});

myPool.connect();

Here is my post route:

const router = express.Router();

router.post("/item/new", async (request, response) =>{
try{
    const { itemTitle } = request.body;
    const myItem = await myPool.query(`INSERT INTO items VALUES('${itemTitle}')`), (resp, err) =>{
            if(err){
                return err;
            }
            
            return resp;
        });
    return response.status(201).json({message: myItem});
}catch(err){
    return response.status(400).json({message: `${err}`});
}

});

When I send the request, I get the following response with a 201 status code, but nothing
is inserted into the database:

{
    "message": {}
}

2

Answers


  1. It’s because you’re sending the callback function with the wrong argument’s order. The first argument for the callback is error, not result.

    It should be like this:

    client.query('SELECT NOW() as now', (error, result) => {
      if (error) {
        console.log(error.stack)
      } else {
        console.log(result.rows[0])
      }
    })
    

    documentation.

    Login or Signup to reply.
  2. You can try to print the query that you are passing to find the error.

    The reason is that you are concatenating a json object with string which is wrong, instead try this:

    `INSERT INTO items(col1, col2) VALUES(${itemTitle.col1}, ${itemTitle.col2})`
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search