Home > Net >  Data not getting inserted into database, despite of 201 request status - postgresql express js
Data not getting inserted into database, despite of 201 request status - postgresql express js

Time:01-17

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": {}
}

CodePudding user response:

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.

CodePudding user response:

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})`
  • Related