簡體   English   中英

NodeJS-將標頭發送到客戶端后無法設置標頭

[英]NodeJS - Cannot set Headers after they are sent to the client

因此,我進行了搜索,發現要解決上述問題,我必須在發送響應后返回。 但是我的問題是,即使我回來了,我仍然會遇到錯誤。

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
}

我要產生錯誤的原因是,如果記錄存在,它將進入上面的代碼塊。 除了該特定的代碼塊之外,我在其他地方均未遇到該錯誤。 即使我遇到錯誤,代碼也可以正常工作。

你不能違背諾言鏈return關鍵字,所有.then語句將被執行(排除你在拋出一個錯誤.then ),該res.json已經被多次調用。

在catch塊中處理所有錯誤(包括您的錯誤和系統錯誤)。

在catch塊中,檢查您是否拋出了錯誤以返回響應。

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
}
const dbEditCourse = (req, res, db, logger) => {
    let {
        origCourse, code, description, type
    } = req.body;
    if (!(code && description && type)) {
        res.json({
            haveEmpty: true
        });
        return;
    } else { // Please Try this. 
        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
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM