16

I'm working with PostgreSQL and NodeJS with its "PG Module". CRUD works but sometimes doesn't update automatically the views when i save or delete some item. this is my code and I think that the error is here but i cannot find it, i tried everything :'(

Error Message:

enter image description here

const controller = {};
const { Pool } = require('pg');

var connectionString = 'postgres://me:system@localhost/recipebookdb';
const pool = new Pool({
    connectionString: connectionString,
})

controller.list = (request, response) => {
    pool.query('SELECT * FROM recipes', (err, result) => {
        if (err) {
            return next(err);
        }
           return response.render('recipes', { data: result.rows });
    });
};

controller.save = (req, res) => {
    pool.query('INSERT INTO recipes(name, ingredients, directions) VALUES ($1, $2, $3)',
        [req.body.name, req.body.ingredients, req.body.directions]);
    return res.redirect('/');
};

controller.delete = (req, res) => {
    pool.query('DELETE FROM RECIPES WHERE ID = $1', [req.params.id]);
    return res.redirect('/');
}

module.exports = controller;

PD: CRUD works but sometimes appears that error.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
timadito
  • 256
  • 1
  • 3
  • 16
  • 1
    Please post the exception as text, not an image. That makes your question more searchable, and easier to read. – Wai Ha Lee Jan 22 '19 at 05:42

3 Answers3

27

This error occurs when you sent a response before and then you try to send response again. For this you have to check if there is any piece of code that is sending your response twice. Sometimes it happens due to asynchronous behavior of nodejs. Sometimes a process will be in event loop and we send response and when it finishes execution response will be sent again. So You can use callbacks or async await to wait for execution.

Callback

const controller = {};
const { Pool } = require('pg');

var connectionString = 'postgres://me:system@localhost/recipebookdb';
const pool = new Pool({
    connectionString: connectionString,
})

controller.list = (request, response) => {
    pool.query('SELECT * FROM recipes', (err, result) => {
        if (err) {
            return next(err);
        }
           return response.render('recipes', { data: result.rows });
    });
};

controller.save = (req, res) => {
    pool.query('INSERT INTO recipes(name, ingredients, directions) VALUES ($1, $2,$3)',
        [req.body.name, req.body.ingredients, req.body.directions],function(err,resp) 
       {
         if(err){
          console.log(err)
      }else{
          return res.redirect('/');
      }
       });
};

controller.delete = (req, res) => {
    pool.query('DELETE FROM RECIPES WHERE ID = $1',  [req.params.id],function(err,resp){
     if(err){
          console.log(err)
      }else{
          return res.redirect('/');
      }
 });
}

module.exports = controller;

Or You can also use async await to wait for execution and then send response.

Async/Await

const controller = {};
const { Pool } = require('pg');

var connectionString = 'postgres://me:system@localhost/recipebookdb';
    const pool = new Pool({
    connectionString: connectionString,
})

controller.list = async(request, response) => {
   try{
       const result = await pool.query('SELECT * FROM recipes');
       return response.render('recipes', { data: result.rows });
   }
    catch(err){
       return next(err);
   }
};

controller.save = async(req, res) => {
    try{
       await pool.query('INSERT INTO recipes(name, ingredients, directions) VALUES ($1, $2,$3)',[req.body.name, req.body.ingredients, req.body.directions]);
       return res.redirect('/');
   }
    catch(err){
       return next(err);
   }
};

controller.delete = async(req, res) => {
    try{
        await pool.query('DELETE FROM RECIPES WHERE ID = $1', [req.params.id]);
        return res.redirect('/');
    }catch(err){
       console.log(err);
    }
}

module.exports = controller;
Zunnurain Badar
  • 920
  • 2
  • 7
  • 28
1

Check res.send() should not call two times.

In Controller

const getAll = function(req, res){
   res.send(service.getAll(req,res));
  }

In Service

const Type = require("../models/type.model.js");
exports.getAll = (req, res) => {
  Type.getAll((err, data) => {  
    res.send(data);
  });
};

Above res.send(data); two-time calling will create a problem. better to use

const getAll = function(req, res){
        service.getAll(req,res);
      }
Atul Jain
  • 1,035
  • 2
  • 16
  • 24
  • Just as an addition: I was following a tutorial setting up a MEAN stack. I left a `res.send('text');` in above an array, then I used `res.json(array)` to send something on res again. Once I removed the useless `res.send()` it was fine. – ntgCleaner Dec 09 '21 at 05:53
0

You need to embed your response in the callback to the query. Since the call is asynchronous, sending the response earlier will terminate the call stack never waiting for the webapi(Behaviour may vary).

controller.delete = (req, res) => {
    pool.query('DELETE FROM RECIPES WHERE ID = $1', [req.params.id],(err, result) 
     => {
         // error handling can be done accordingly
        return res.redirect('/');
    })

}