[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

后端 未结 3 954
广开言路
广开言路 2021-02-19 18:28

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 cod

相关标签:
3条回答
  • 2021-02-19 18:52

    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('/');
        })
    
    }
    
    0 讨论(0)
  • 2021-02-19 18:58

    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;
    
    0 讨论(0)
  • 2021-02-19 19:01

    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);
          }
    
    0 讨论(0)
提交回复
热议问题