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

后端 未结 3 915
广开言路
广开言路 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条回答
  •  旧时难觅i
    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;
    

提交回复
热议问题