[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后,无法设置标头 [英] [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

查看:1262
本文介绍了[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后,无法设置标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PostgreSQL和NodeJS的 PG模块。
CRUD可以运行,但是当我保存或删除某些项目时,有时不会自动更新视图。这是我的代码,我认为错误在这里,但我找不到它,我尝试了所有的方法:'(

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 :'(

错误消息:

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有效,但有时会出现该错误。

PD: CRUD works but sometimes appears that error.

推荐答案

在您之前发送响应,然后尝试再次发送响应时,会发生此错误。为此,您必须检查是否有任何一段代码发送了两次响应。有时由于nodejs的异步行为而发生。有时,一个流程将进入事件循环,我们发送响应,完成后,将再次发送响应。因此,您可以使用回调或异步等待来等待执行。

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.

回调

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.

异步/等待

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;

这篇关于[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后,无法设置标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆