admin管理员组

文章数量:1180542

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:

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.

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:

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.

Share Improve this question edited Jan 22, 2019 at 5:40 Wai Ha Lee 8,80598 gold badges59 silver badges94 bronze badges asked Jan 22, 2019 at 5:13 timaditotimadito 2661 gold badge3 silver badges16 bronze badges 1
  • 1 Please post the exception as text, not an image. That makes your question more searchable, and easier to read. – Wai Ha Lee Commented Jan 22, 2019 at 5:42
Add a comment  | 

3 Answers 3

Reset to default 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;

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);
      }

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('/');
    })

}

本文标签: javascriptERRHTTPHEADERSSENT Cannot set headers after they are sent to the clientStack Overflow