NodeJS-将标头发送到客户端后无法设置标头 [英] NodeJS - Cannot set Headers after they are sent to the client

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

问题描述

因此,我四处搜寻,发现要解决上述问题,我必须在发送回复后返回.但是我的问题是,即使我回来了,我仍然会遇到错误.

So I've searched around and found out that to fix the said issue, I have to return after sending a response. But my problem is, even though I have return, I still have the error.

const dbEditCourse = (req, res, db, logger) => {
    let {
        origCourse, code, description, type
    } = req.body;
    if (!code || !description || !type) {
        res.json({
            haveEmpty: true
        });
        return;
    }
    db.transaction((trx) => {
            db.select('*').from('course_strand').where('code', '=', code)
                .then(data => {
                    if (data[0]) {

                        //error happens in this block of code
                        res.json({
                            isSuccess: false
                        });
                        return;
                        //i also tried return res.json({ isSuccess: false });

                    }
                    //wrapping this in 'else' also does not work
                    return db('course_strand')
                        .returning('*')
                        .where('code', '=', origCourse)
                        .update({ code, description, type })
                })
                .then(course => {
                    return db('activity_logs')
                        .returning('*')
                        .insert({
                            date: new Date(),
                            employee_id: req.session.emp_id,
                            module: "COURSE / STRAND",
                            activity: "EDIT"
                        })
                })
                .then(activity => {
                    if (activity[0]) {
                        res.json({
                            isSuccess: true
                        });
                        return;
                    } else {
                        res.json({
                            isSuccess: false
                        });
                        return;
                    }
                })
                .then(trx.commit)
                .catch(err => {
                    logger.error(err);
                    trx.rollback;
                    res.render('pages/error-500');
                });
        })
        .catch(err => logger.error(err));
}

module.exports = {
    dbEditCourse
}

我要产生错误的原因是,如果记录存在,它将进入上面的代码块.除了该特定的代码块之外,我在其他地方都没有遇到该错误.即使出现错误,代码也可以正常工作.

What I'm doing to produce the error is, If the record is existing, it will go into the block of code above. Aside from that specific block of code, I don't encounter the error elsewhere. And the code is working fine even though I have the error.

推荐答案

您不能使用return关键字破坏promise链,将执行所有.then语句(不包括在.then中引发错误),res.json被调用过很多次.

You cannot break a promise chain with return keyword, all .then statements will be executed (exclude you throw an error in a .then), the res.json has been called many times.

处理catch块中的所有错误(包括您的错误和系统错误).

Handler all errors (include your error and system error) in catch block.

在catch块中,检查您是否抛出了错误以返回响应.

In catch block, check the error is throwing by you or not to return the response.

const dbEditCourse = (req, res, db, logger) => {
  let {
    origCourse, code, description, type
  } = req.body;
  if (!code || !description || !type) {
    res.json({
      haveEmpty: true
    });
    return;
  }

  // util throw a error
  const breakWithMyError = () => {
    throw new Error("MY_ERROR");
  }

  db.transaction((trx) => {
    db.select('*').from('course_strand').where('code', '=', code)
      .then(data => {
        if (data[0]) {

          //error happens in this block of code
          breakWithMyError();
          //i also tried return res.json({ isSuccess: false });

        }
        //wrapping this in 'else' also does not work
        return db('course_strand')
          .returning('*')
          .where('code', '=', origCourse)
          .update({ code, description, type })
      })
      .then(course => {
        return db('activity_logs')
          .returning('*')
          .insert({
            date: new Date(),
            employee_id: req.session.emp_id,
            module: "COURSE / STRAND",
            activity: "EDIT"
          })
      })
      .then(activity => {
        // revert logic, we check for error case first
        if (!activity[0]) {
          breakWithMyError();
        }
      })
      .then(trx.commit)
      .then(() => {
        // finally you can run to here without any error
        res.json({
          isSuccess: true
        });
      })
      .catch(err => {
        // If you any error, the error comes form `breakWithMyError` or any things.
        if (err.message === "MY_ERROR") {
          // the error throw by `breakWithMyError`
          return res.json({
            isSuccess: false
          });
        }
        logger.error(err);
        trx.rollback;
        // Why you return a html page in failed case? `res.status(500).json({message: "Internal server!"});`
        res.render('pages/error-500');
      });
  })
    .catch(err => logger.error(err));
}

module.exports = {
  dbEditCourse
}

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

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